Chapter 9: Lists
9.1 Introduction to Lists
A list is an ordered, mutable (changeable) collection of elements. Elements
can be of different data types (integers, strings, floats, etc.), and even other
lists.
Syntax: Elements of a list are enclosed in square brackets [ ] and separated
by commas.
Example:
list1 = [2, 4, 6, 8, 10]
list2 = ['a', 'e', 'i', 'o', 'u']
list3 = [100, 23.5, 'Hello']
9.1.1 Accessing Elements in a List
Indexing: Access elements by their index (starting from 0). Negative indices
access elements from the end.
Example:
list1 = [2, 4, 6, 8, 10]
print(list1[0]) # 2 (first element)
print(list1[3]) # 8 (fourth element)
print(list1[-1]) # 10 (last element)
Index Error: Trying to access an out-of-range index will give an error.
Example:
list1[10] # IndexError: list index out of range
9.1.2 Lists are Mutable
Lists can be changed after creation (e.g., modifying elements, adding, or
removing items).
Example:
list1 = ['Red', 'Green', 'Blue', 'Orange']
list1[3] = 'Black' # Changing 'Orange' to 'Black'
print(list1) # ['Red', 'Green', 'Blue', 'Black']
9.2 List Operations
9.2.1 Concatenation
You can combine two or more lists using the + operator.
Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
print(list1 + list2) # [1, 2, 3, 4, 5, 6]
9.2.2 Repetition
You can repeat a list multiple times using the * operator.
Example:
list1 = ['Hello']
print(list1 * 3) # ['Hello', 'Hello', 'Hello']
9.2.3 Membership
Use the in keyword to check if an item is present in a list.
Example:
list1 = ['Red', 'Green', 'Blue']
print('Green' in list1) # True
print('Yellow' in list1) # False
9.2.4 Slicing
Slicing lets you extract a part of the list by specifying a range of indices.
Syntax: list[start:end]
Example:
list1 = ['Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']
print(list1[2:5]) # ['Blue', 'Cyan', 'Magenta']
print(list1[:4]) # ['Red', 'Green', 'Blue', 'Cyan']
print(list1[::2]) # ['Red', 'Blue', 'Magenta', 'Black']
print(list1[::-1]) # ['Black', 'Yellow', 'Magenta', 'Cyan', 'Blue', 'Green',
'Red']
9.3 Traversing a List
You can access each element of a list using a loop.
Using for loop:
list1 = ['Red', 'Green', 'Blue', 'Yellow', 'Black']
for item in list1:
print(item)
Output:
Red
Green
Blue
Yellow
Black
Using range() with for loop:
for i in range(len(list1)):
print(list1[i])
Using while loop:
i=0
while i < len(list1):
print(list1[i])
i += 1
9.4 LIST METHODS AND BUILT-IN FUNCTIONS
The data type list has several built-in methods that are useful in programming.
Here’s a table summarizing the methods for list operations in Python:
Method Description Example
Returns the length of the list passed as list1 = [10, 20, 30, 40, 50]
len()
the argument. len(list1) returns 5
Creates an empty list if no argument is
str1 = 'aeiou' list1 = list(str1)
list() passed. Creates a list if a sequence is
returns ['a', 'e', 'i', 'o', 'u']
passed as an argument.
Appends a single element passed as an list1 = [10, 20, 30]
append() argument at the end of the list. The single list1.append(40) makes list1
element can also be a list. [10, 20, 30, 40]
Appends each element of the list passed list1 = [10, 20] list2 = [30, 40]
extend() as an argument to the end of the given list1.extend(list2) makes list1
list. [10, 20, 30, 40]
list1 = [10, 20, 30]
Inserts an element at a particular index in
insert() list1.insert(1, 15) makes list1
the list.
[10, 15, 20, 30]
Returns the number of times a given list1 = [10, 20, 10, 30, 10]
count()
element appears in the list. list1.count(10) returns 3
Returns the index of the first occurrence
list1 = [10, 20, 30, 40]
index() of the element in the list. If the element is
list1.index(20) returns 1
not present, ValueError is raised.
Removes the given element from the list.
If the element is present multiple times, list1 = [10, 20, 30, 20]
remove() only the first occurrence is removed. If list1.remove(20) makes list1
the element is not present, ValueError is [10, 30, 20]
raised.
Returns the element whose index is
list1 = [10, 20, 30, 40]
passed as a parameter and also removes
pop() list1.pop() removes 40 and
it from the list. If no parameter is given,
returns it.
it removes and returns the last element.
list1 = ['Tiger', 'Zebra', 'Lion',
reverse() Reverses the order of elements in the list.
'Cat'] list1.reverse() makes
Method Description Example
list1 ['Cat', 'Lion', 'Zebra',
'Tiger']
list1 = ['Tiger', 'Zebra', 'Lion',
Sorts the elements of the given list in-
sort() 'Cat'] list1.sort() makes list1
place.
['Cat', 'Lion', 'Tiger', 'Zebra']
Takes a list as a parameter and creates a
list1 = [3, 1, 4, 2] sorted(list1)
sorted() new list consisting of the same elements
returns [1, 2, 3, 4]
arranged in sorted order.
Returns the minimum (smallest) element list1 = [10, 20, 30] min(list1)
min()
of the list. returns 10
Returns the maximum (largest) element list1 = [10, 20, 30] max(list1)
max()
of the list. returns 30
Returns the sum of the elements in the list1 = [10, 20, 30] sum(list1)
sum()
list. returns 60
9.5 Nested Lists
A nested list occurs when a list is an element of another list. Here’s the basic
example:
list1 = [1, 2, 'a', 'c', [6, 7, 8], 4, 9]
In this example, the fifth element of list1 is itself a list: [6, 7, 8]. You can access
this nested list by referring to the correct index:
list1[4] # Output: [6, 7, 8]
To access elements within the nested list, you use two indices: the first to get to
the nested list and the second to get the element inside it:
list1[4][1] # Output: 7 (Second element in the nested list)
9.6 Copying Lists
When you assign one list to another using the = operator, the two lists will
reference the same object in memory. Any changes to one list will reflect in the
other.
list1 = [1, 2, 3]
list2 = list1
list1.append(10)
print(list1) # Output: [1, 2, 3, 10]
print(list2) # Output: [1, 2, 3, 10] (both lists are the same)
To create an actual copy (i.e., a new object), you can use several methods:
Method 1: Using slicing
newList = oldList[:]
Example:
list1 = [1, 2, 3, 4, 5]
list2 = list1[:] # Copy of list1
print(list2) # Output: [1, 2, 3, 4, 5]
Method 2: Using list()
newList = list(oldList)
Example:
list1 = [10, 20, 30, 40]
list2 = list(list1)
print(list2) # Output: [10, 20, 30, 40]
Method 3: Using copy.copy()
import copy
newList = copy.copy(oldList)
Example:
import copy
list1 = [1, 2, 3, 4, 5]
list2 = copy.copy(list1)
print(list2) # Output: [1, 2, 3, 4, 5]
9.7 Lists as Arguments to a Function
When you pass a list to a function, Python uses pass-by-reference, meaning that
changes made inside the function will affect the original list.
Scenario A: Modifying the list
def increment(list2):
for i in range(0, len(list2)):
list2[i] += 5
print('Reference of list inside function:', id(list2))
list1 = [10, 20, 30, 40, 50]
print("Reference of list in main:", id(list1))
print("Before function call:", list1)
increment(list1) # list1 is passed to the function
print("After function call:", list1)
Output:
Reference of list in main: <some memory address>
Before function call: [10, 20, 30, 40, 50]
Reference of list inside function: <same memory address>
After function call: [15, 25, 35, 45, 55]
Exercise Solutions:
1. What will be the output of the following statements?
i.
list1 = [12,32,65,26,80,10]
list1.sort()
print(list1)
Output:
[10, 12, 26, 32, 65, 80]
list1.sort() sorts the list in ascending order.
ii.
list1 = [12,32,65,26,80,10]
sorted(list1)
print(list1)
Output:
[12, 32, 65, 26, 80, 10]
sorted(list1) returns a new sorted list, but list1 remains unchanged because
sorted() does not modify the original list.
iii.
list1 = [1,2,3,4,5,6,7,8,9,10]
print(list1[::-2])
print(list1[:3] + list1[3:])
Output:
[10, 8, 6, 4, 2]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list1[::-2] gives every second element in reverse order, and list1[:3] +
list1[3:] concatenates the first three elements with the rest of the list.
iv.
list1 = [1,2,3,4,5]
print(list1[len(list1)-1])
Output:
5
len(list1)-1 gives the index of the last element, which is 5.
2. Consider the following list myList. What will be the elements of myList
after the following two operations:
3. myList = [10,20,30,40]
4. myList.append([50,60])
5. print(myList)
6. myList.extend([80,90])
7. print(myList)
Output:
[10, 20, 30, 40, [50, 60]]
[10, 20, 30, 40, [50, 60], 80, 90]
append([50, 60]) adds the list [50, 60] as a single element, whereas
extend([80, 90]) adds the elements 80 and 90 to the list.
8. What will be the output of the following code segment?
myList = [1,2,3,4,5,6,7,8,9,10]
for i in range(0, len(myList)):
if i % 2 == 0:
print(myList[i])
Output:
1
3
5
7
9
The loop prints every element at an even index.
9. What will be the output of the following code segment?
a.
myList = [1,2,3,4,5,6,7,8,9,10]
del myList[3:]
print(myList)
Output:
[1, 2, 3]
del myList[3:] deletes all elements from index 3 onwards.
b.
myList = [1,2,3,4,5,6,7,8,9,10]
del myList[:5]
print(myList)
Output:
[6, 7, 8, 9, 10]
del myList[:5] deletes the first five elements.
c.
myList = [1,2,3,4,5,6,7,8,9,10]
del myList[::2]
print(myList)
Output:
[2, 4, 6, 8, 10]
del myList[::2] removes elements at even indices.
10. Differentiate between append() and extend() functions of list.
o append() adds a single element to the end of the list.
o extend() adds each element of an iterable (e.g., list, tuple) to the end
of the list.
11. Consider a list:
list1 = [6,7,8,9]
What is the difference between the following operations on list1:
a. list1 * 2
Result:
[6, 7, 8, 9, 6, 7, 8, 9]
This creates a new list by repeating list1 twice.
b. list1 *= 2
Result:
[6, 7, 8, 9, 6, 7, 8, 9]
This modifies the original list1 by repeating it.
c. list1 = list1 * 2
Result:
[6, 7, 8, 9, 6, 7, 8, 9]
This creates a new list by repeating list1 twice and assigns it back to list1.
12. The record of a student (Name, Roll No., Marks in five subjects, and
percentage of marks) is stored in the following list:
stRecord = ['Raman', 'A-36', [56, 98, 99, 72, 69], 78.8]
Write Python statements to retrieve the following information from the list
stRecord:
a) Percentage of the student
print(stRecord[3]) # 78.8
b) Marks in the fifth subject
print(stRecord[2][4]) # 69
c) Maximum marks of the student
print(max(stRecord[2])) # 99
d) Roll no. of the student
print(stRecord[1]) # 'A-36'
e) Change the name of the student from ‘Raman’ to ‘Raghav’
stRecord[0] = 'Raghav'
print(stRecord) # ['Raghav', 'A-36', [56, 98, 99, 72, 69], 78.8]