Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Py Module 3

The document discusses lists in Python. It defines what a list is, how to create and access list items, and common list methods like append(), insert(), remove(), pop(), and sort(). It also covers looping through lists, joining lists, nested lists, and other list operations in Python.

Uploaded by

abmunavar11
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Py Module 3

The document discusses lists in Python. It defines what a list is, how to create and access list items, and common list methods like append(), insert(), remove(), pop(), and sort(). It also covers looping through lists, joining lists, nested lists, and other list operations in Python.

Uploaded by

abmunavar11
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

MODULE 3

List Structures - Common List Operations - List Traversal - Lists (Sequences) in


Python- Python List Type - Tuples- Sequences- Nested Lists Iterating Over
Lists (Sequences) in Python - For Loops - The Built-in range Function -
Iterating Over List Elements vs. List Index Values-While Loops and Lists
(Sequences) - Dictionaries and sets

List
A list refers to a collection of objects; it represents an ordered sequence of
data. In that sense, a list is similar to a string, except a string can hold only
characters. We may access the elements contained in a list via their position
within the list. A list need not be homogeneous; that is, the elements of a list do
not all have to be of the same type.

Lists are one of 4 built-in data types in Python used to store collections of
data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and
usage.

Lists are created using square brackets:


Create a List:

fruits = ["apple", "banana", "cherry"]


print(fruits)

List Items
List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has index [1]
etc.

Ordered
When we say that lists are ordered, it means that the items have a defined order,
and that order will not change.

If you add new items to a list, the new items will be placed at the end of the list.

List Methods
Python has a set of built-in methods that you can use on lists.

Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list

J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605


copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current
list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))

Accessing List
Example-1
Return the third, fourth, and fifth item:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[2:5])

Example-2
This example returns the items from the beginning to, but NOT including,
"kiwi":

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[:4])

Example-3
This example returns the items from "cherry" to the end:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[2:])

Check if Item Exists


To determine if a specified item is present in a list use the in keyword:

Example
J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605
Check if "apple" is present in the list:

thislist = ["apple", "banana", "cherry"]


if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")

Change Item Value


To change the value of a specific item, refer to the index number:

Example

Change the second item:

thislist = ["apple", "banana", "cherry"]


thislist[1] = "blackcurrant"
print(thislist)

Append Items
To add an item to the end of the list, use the append() method:

Example
Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]


thislist.append("orange")
print(thislist)

Insert Items
To insert a list item at a specified index, use the insert() method.

The insert() method inserts an item at the specified index:

Example
Insert an item as the second position:

thislist = ["apple", "banana", "cherry"]


thislist.insert(1, "orange")
print(thislist)

J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605


Remove Specified Item
The remove() method removes the specified item.

Example:
Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Output:
['apple', 'cherry']

Remove Specified Index


The pop() method removes the specified index.

Example Remove the second item:

thislist = ["apple", "banana", "cherry"]


thislist.pop(1)
print(thislist)
Output:
['apple', 'cherry']
Loop Through a List
We can loop through the list items by using a for loop:
Example
Print all items in the list, one by one:

thislist = ["apple", "banana", "cherry"]


for x in thislist:
print(x)
Output
apple
banana
cherry

Sort List Alphanumerically


List objects have a sort() method that will sort the list alphanumerically,
ascending, by default:
Example
Sort the list alphabetically:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
Output
J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605
['banana', 'kiwi', 'mango', 'orange', 'pineapple']

Example
Sort the list numerically:
thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)
Output
[23, 50, 65, 82, 100]

Sort Descending
To sort descending, use the keyword argument reverse = True:

Example
Sort the list descending:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
Output
['pineapple', 'orange', 'mango', 'kiwi', 'banana']

Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only be
a reference to list1, and changes made in list1 will automatically also be made
in list2.

There are ways to make a copy, one way is to use the built-in List method
copy().

Example
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
Output
['apple', 'banana', 'cherry']

Join Two Lists


There are several ways to join, or concatenate, two or more lists in Python.

One of the easiest ways are by using the + operator.

J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605


Example
Join two list:

list1 = ["a", "b", "c"]


list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Output
['a', 'b', 'c', 1, 2, 3]
Another way to join two lists is by appending all the items from list2 into list1,
one by one:

Example
Append list2 into list1:

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

for x in list2:
list1.append(x)
print(list1)
Output
['a', 'b', 'c', 1, 2, 3]

Or we can use the extend() method, which purpose is to add elements from one
list to another list:

Example
Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
Output
['a', 'b', 'c', 1, 2, 3]

J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605


List Items - Data Types
List items can be of any data type:
Example: String, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

Dictionaries and Sets in python


Method 1: Using the Naive Method
In this method, we create a dictionary of sets by passing sets as values to the
keys.

Syntax
{ „Key‟: Set 1, „Key‟:Set 2,…………..,‟Key‟: Set n}

Algorithm (Steps)
Following are the Algorithms/steps to be followed to perform the desired task. −

Create a variable to store the dictionary containing the values as a set without
duplicate elements (i.e, dictionary of sets).

Print the input dictionary of sets.

Example
The following program creates a dictionary of sets(without duplicates) in python
using the Naive Method −

# creating a dictionary containing the values as set


# without duplicate elements
# (dictionary of sets)
inputDict = { 'Employ ID': {10, 11, 12, 14, 15},
'Employ Age': {25, 30, 40, 35, 28}}

# printing the input dictionary of sets


print(inputDict)

Output
On execution, the above program will generate the following output −

{'Employ ID': {10, 11, 12, 14, 15}, 'Employ Age': {35, 40, 25, 28, 30}}

J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605


Creating a Set having Duplicates
In general, the set in python does not allow duplicates i,e which removes all the
repeated elements.

Example
The below example shows that a python set will not allow duplicates.

The following program creates a dictionary of sets(containing duplicates) in


python using the Naive Method −

# creating a dictionary containing the values as set


# with duplicates elements
# the set does not allow duplicates
inputDict = {'Employ ID': {10, 11, 12, 13, 13, 14, 15, 10, 12, 11},
'Employ Age': {25, 30, 30, 40, 25, 35, 40, 28, 33, 25}}

# printing the input dictionary


print(inputDict)
Output
On executing, the above program will generate the following output −

{'Employ ID': {10, 11, 12, 13, 14, 15}, 'Employ Age': {33, 35, 40, 25, 28, 30}}
In the above example, we can observe that all the duplicates are removed, and
printed only the unique elements. Hence proved that a python set removes does
not allow duplicates.

Method 2: Using defaultdict() Method


In this method, the default set will be created and the key-values pairs will be
passed to it.

Syntax
defaultdict(set)
Passing the dictionary with key and value −

dictionary[“key”] |= {„value1‟, „value2′, ……………,‟value n‟}


Here,

dictionary − input dictionary


key − key of a dictionary
value − the value of a dictionary passed as set.

Algorithm (Steps)
Following are the Algorithms/steps to be followed to perform the desired task. −

J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605


Use the import keyword to import the defaultdict from the collections module.

Use the defaultdict() method, to create an empty set of dictionary using the by-
passing set as an argument to it.

Give the key-value pairs for the dictionary using the [] operator.

Print the created dictionary of sets.

Example
The following program creates a dictionary of sets in python using the
defaultdict() function −

# importing defaultdict from the collections module


from collections import defaultdict

# creating an empty set of the dictionary using the


# defaultdict() method by passing set as argument to it
dictionary = defaultdict(set)

# giving the first key-value pair of a dictionary


dictionary["Employ ID"] |= {10, 11, 12, 14, 15}

# giving the second key-value pair of a dictionary


dictionary["Employ Age"] |= {25, 30, 40, 35, 28}

# printing the created dictionary of sets


print(dictionary)
Output
On execution, the above program will generate the following output −

defaultdict(<class 'set'>,
{'Employ ID': {10, 11, 12, 14, 15},
'Employ Age': {35, 40, 25, 28, 30}})

J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605

You might also like