0% found this document useful (0 votes)
18 views7 pages

Chapter 9 Lists

The document provides a comprehensive overview of lists in Python, detailing their characteristics, operations, and methods. It covers topics such as accessing elements, mutability, list operations like concatenation and slicing, and methods for list manipulation. Additionally, it explains nested lists and how to copy lists, along with the implications of passing lists as arguments to functions.

Uploaded by

Saraswathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views7 pages

Chapter 9 Lists

The document provides a comprehensive overview of lists in Python, detailing their characteristics, operations, and methods. It covers topics such as accessing elements, mutability, list operations like concatenation and slicing, and methods for list manipulation. Additionally, it explains nested lists and how to copy lists, along with the implications of passing lists as arguments to functions.

Uploaded by

Saraswathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

 INTRODUCTION TO LIST

 Accessing Elements in a List


 Lists are Mutable
 LIST OPERATIONS
 TRAVERSING A LIST
 Copy a list
 Nested list

9.1 INTRODUCTION TO LIST


 The data type list is an ordered sequence which is mutable and made up of one or more elements.
 Elements of a list are enclosed in square brackets and are separated by comma.
 A string which consists of only characters, a list can have elements of different data types, such as
integer, float, string, tuple or even another list.

#list1 is the list of six even numbers


>>> list1 = [2,4,6,8,10,12]
>>> print(list1)
[2, 4, 6, 8, 10, 12]
#list2 is the list of vowels
>>> list2 = ['a','e','i','o','u']
>>> print(list2)
['a', 'e', 'i', 'o', 'u']
#list3 is the list of mixed data types
>>> list3 = [100,23.5,'Hello']
>>> print(list3)
[100, 23.5, 'Hello']
#list4 is the list of lists called nested
#list
>>> list4 =[['Physics',101],['Chemistry',202],
['Maths',303]]
>>> print(list4)
[['Physics', 101], ['Chemistry', 202],
['Maths', 303]]

9.1.1 Accessing Elements in a List


 The elements of a list are accessed using index.
>>> list1 = [2,4,6,8,10,12] #initializes a list list1
>>> list1[0] #return first element of list1
2
>>> list1[3] #return fourth element of list1
8 #return error as index is out of range
>>> list1[15]
IndexError: list index out of range
>>> list1[1+4] #an expression resulting in an integer index
12
>>> list1[-1] #return first element from right
12
>>> n = len(list1) #length of the list list1 is assigned to n
>>> print(n)
6
>>> list1[n-1] #return the last element of the list1
12
>>> list1[-n] #return the first element of list1
2

9.1.2 Lists are Mutable


 Lists are mutable.
 It means that the contents of the list can be changed after it has been created.

#List list1 of colors


>>> list1 = ['Red','Green','Blue','Orange'] #change/override the fourth element of list1
>>> list1[3] = 'Black'
>>> list1 #print the modified list list1
['Red', 'Green', 'Blue', 'Black']

9.2 LIST OPERATIONS


 Concatenation ;
 Repetition ;
 Membership ;
 Slicing ;

1 Concatenation:
 To join two or more lists using concatenation operator depicted by the symbol +.

#list1 and list2 is list of first five odd integers


>>> list1 = [1,3,5,7,9]
>>> list2 = [2,4,6,8,10]
>>> list1 + list2 #elements of list1 followed by list2
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
>>> list3 = ['Red','Green','Blue']
>>> list4 = ['Cyan', 'Magenta', 'Yellow' ,'Black']
>>> list3 + list4 #['Red','Green','Blue','Cyan','Magenta', 'Yellow','Black']

2 Repetition:
 Python allows us to replicate a list using repetition operator depicted by symbol *.

>>> list1 = ['Hello']


>>> list1 * 4 #elements of list1 repeated 4 times
['Hello', 'Hello', 'Hello', 'Hello']

3 Membership:
 The in operator checks if the element is present in the list and returns True, else returns False.
 The not in operator returns True if the element is not present in the list, else it returns False.

>>> list1 = ['Red','Green','Blue']


>>> 'Green' in list1
True
>>> 'Cyan' not in list1
True
>>> 'Green' not in list1
False

4 Slicing: the slicing operation can also be applied to lists.


>>> list1 =['Red','Green','Blue','Cyan', 'Magenta','Yellow','Black']
>>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow']
>>>list1[2:20] #second index is out of range
['Blue', 'Cyan', 'Magenta', 'Yellow','Black']
>>> list1[7:2] #first index > second index #results in an empty list
[]
>>> list1[:5] #return sublist from index 0 to 4
['Red','Green','Blue','Cyan','Magenta']

>>> list1[0:6:2] #slicing with a given step size


['Red','Blue','Magenta']

>>> list1[-6:-2] #elements at index -6,-5,-4,-3 are sliced


['Green','Blue','Cyan','Magenta']

>>> list1[::2] #both first and last index missing


['Red','Blue','Magenta','Black']

#negative step size


#whole list in the reverse order
>>> list1[::-1]
['Black','Yellow','Magenta','Cyan','Blue', 'Green','Red']

9.3 TRAVERSING A LIST:


We can access each element of the list or traverse a list using a for loop or a while loop.
(A) List Traversal Using for Loop:
>>> list1 = ['Red','Green','Blue','Yellow', 'Black']
>>> for item in list1:
print(item)

Another way of accessing the elements of the list is using range() and len() functions
>>> for i in range(len(list1)):
print(list1[i])

(B) List Traversal Using while Loop:


>>> list1 = ['Red','Green','Blue','Yellow',
'Black']
>>> i = 0
>>> while i < len(list1):
print(list1[i])
i += 1
Output: Red
Green
Blue
Yellow
Black

9.4 LIST METHODS AND BUILT-IN FUNCTIONS


len(): Returns the length of the list passed as the argument
>>> list1 = [10,20,30,40,50]
>>> len(list1)
5

list() : Creates an empty list if no argument is passed


Creates a list if a sequence is passed as an argument the occurrence Is first only insert()
>>> list1 = list()
>>> list1
[]
>>> str1 = 'aeiou'
>>> list1 = list(str1)
>>> list1
['a', 'e', 'i', 'o', 'u']

append() : Appends a single element passed as an argument at the end of the list. The single element can
also be a list
>>> list1 = [10,20,30,40]
>>> list1.append(50)
>>> list1
[10, 20, 30, 40, 50]
>>> list1 = [10,20,30,40]
>>> list1.append([50,60])
>>> list1
[10, 20, 30, 40, [50, 60]]

extend(): Appends each element of the list passed as argument to the end of the given list.
>>> list1 = [10,20,30]
>>> list2 = [40,50]
>>> list1.extend(list2)
>>> list1
[10, 20, 30, 40, 50]

insert(): Inserts an element at a particular index in the list


>>> list1 = [10,20,30,40,50]
>>> list1.insert(2,25)
>>> list1
[10, 20, 25, 30, 40, 50]
>>> list1.insert(0,5)
>>> list1
[5, 10, 20, 25, 30, 40, 50]

count(): Returns the number of times a given element appears in the list
>>> list1 = [10,20,30,10,40,10]
>>> list1.count(10)
3
>>> list1.count(90)
0

index(): Returns index of the first occurrence of the element in the list. If the element is not present,
ValueError is generated
>>> list1 = [10,20,30,20,40,10]
>>> list1.index(20)
1
>>> list1.index(90)
ValueError: 90 is not in list

remove(): Removes the given element from the list. If the element is present multiple times, only the first
occurance is removed. If the element is not present, then ValueError is generated.
>>> list1 = [10,20,30,40,50,30]
>>> list1.remove(30)
>>> list1
[10, 20, 40, 50, 30]
>>> list1.remove(90)
ValueError:list.remove(x):x not in list

pop(): Returns the element whose index is passed as parameter to this function and also removes it from
the list. If no parameter is given, then it returns and removes the last element of the list

>>> list1 = [10,20,30,40,50,60]


>>> list1.pop(3)
40
>>> list1
[10, 20, 30, 50, 60]
>>> list1 = [10,20,30,40,50,60]
>>> list1.pop()
60

reverse() : Reverses the order of elements in the given list


>>> list1 = [34,66,12,89,28,99]
>>> list1.reverse()
>>> list1
[ 99, 28, 89, 12, 66, 34]
>>> list1 = [ 'Tiger' ,'Zebra' , 'Lion' , 'Cat' ,'Elephant' ,'Dog']
>>> list1.reverse()
>>> list1
['Dog', 'Elephant', 'Cat', 'Lion', 'Zebra', 'Tiger']

sort(): Sorts the elements of the given list in-place


>>>list1 = ['Tiger','Zebra','Lion', 'Cat', 'Elephant' ,'Dog']
>>> list1.sort()
>>> list1
['Cat', 'Dog', 'Elephant', 'Lion', 'Tiger', 'Zebra']
>>> list1 = [34,66,12,89,28,99]
>>> list1.sort(reverse = True)
>>> list1
[99,89,66,34,28,12]

sorted():It takes a list as parameter and creates a new list consisting of the same elements arranged in
sorted order
>>> list1 = [23,45,11,67,85,56]
>>> list2 = sorted(list1)

>>> list1
[23, 45, 11, 67, 85, 56]
>>> list2
[11, 23, 45, 56, 67, 85]

min() : Returns minimum or smallest element of the list


max(): Returns maximum or largest element of the list
sum(): Returns sum of the elements of the list
>>> list1 = [34,12,63,39,92,44]
>>> min(list1)
12
>>> max(list1)
92
>>> sum(list1)
284

9.5 NESTED LISTS


When a list appears as an element of another list, it is called a nested list.
>>> list1 = [1,2,'a','c',[6,7,8],4,9] #fifth element of list is also a list
>>> list1[4]
[6, 7, 8]

 To access the element of the nested list of list1,


 we have to specify two indices list1[i][j].
 The first index i will take us to the desired nested list and second index j will take us to the desired
element in that nested list.
>>> list1[4][1]
7

9.6 COPYING LISTS : To make a copy of the list is to assign it to another list.
>>> list1 = [1,2,3]
>>> list2 = list1
>>> list1
[1, 2, 3]
>>> list2
[1, 2, 3]

Method 1
We can slice our original list and store it into a new variable as follows:
newList = oldList[:]

>>> list1 = [1,2,3,4,5]


>>> list2 = list1[:]
>>> list2
[1, 2, 3, 4, 5]

Method 2
We can use the built-in function list() as follows: newList = list(oldList)
>>> list1 = [10,20,30,40]
>>> list2 = list(list1)
>>> list2
[10, 20, 30, 40]

Method 3
We can use the copy () function as follows:
import copy #import the library copy #use copy()function of library copy
newList = copy.copy(oldList)

>>> import copy


>>> list1 = [1,2,3,4,5]
>>> list2 = copy.copy(list1)
>>> list2
[1, 2, 3, 4, 5]

9.7 LIST AS ARGUMENT TO A FUNCTION


Whenever a list is passed as an argument to a function, we have to consider two scenarios:
(A) Elements of the original list may be changed, i.e. changes made to the list in the function are
reflected back in the calling function.

#Function to increment the elements of the list passed as argument


def increment(list2):
for i in range(0,len(list2)):
#5 is added to individual elements in the list
list2[i] += 5
print('Reference of list Inside Function',id(list2))
#end of function
list1 = [10,20,30,40,50] #Create a list
print("Reference of list in Main",id(list1))
print("The list before the function call")
print(list1)
increment(list1) #list1 is passed as parameter to function
print("The list after the function call")
print(list1)

9.8 LIST MANIPULATION


• Append an element
• Insert an element
• Append a list to the given list
• Modify an existing element
• Delete an existing element from its position
• Delete an existing element with a given value
• Sort the list in ascending order
• Sort the list in descending order
• Display the list.

You might also like