Lists are sequences, which means they support common sequence operations that work with other sequence types like strings and tuples. These operations include:
Membership: Check if an element exists
Length: Get the number of elements
Minimum and Maximum: Find the smallest and largest elements
Counting: Count the number of occurrences of an element
Individual elements in a list can be accessed using their index. In Python, indices start at 0, so the first element is at index 0, the second at index 1, and so on.
1
fruits = ["A", "B", "C", "D"]
2
3
print(fruits[0]) # A
4
print(fruits[1]) # B
5
print(fruits[2]) # C
6
print(fruits[3]) # D
Negative indices count from the end of the list. -1 refers to the last element, -2 to the second-to-last, and so on.
1
fruits = ["A", "B", "C", "D"]
2
3
print(fruits[-1]) # D
4
print(fruits[-2]) # C
5
print(fruits[-3]) # B
6
print(fruits[-4]) # A
Warning
Accessing an index that doesn’t exist will raise an IndexError:
1
fruits = ["apple", "banana"]
2
print(fruits[5]) # IndexError: list index out of range
Slicing allows a portion of a list to be extracted. The syntax is list[start:stop:step] where start is the index of the first item to include (inclusive), stop is the index of the first item to exclude (exclusive), and step is the number of items to skip between each item which defaults to 1.
1
x = ["A", "B", "C", "D"]
2
3
print(x[0:2]) #["A", "B"]
4
print(x[1:2]) #["B"]
5
print(x[1:4]) #["B", "C", "D"]
6
print(x[0:4:2]) #["A", "C"]
7
print(x[-1:0:-2]) #["D", "B"]
8
print(x[-1:0:1]) #[]
9
print(x[-4:4]) #["A", "B", "C", "D"]
The start, end and step indices can be omitted. If start is omitted, it defaults to 0. If end is omitted, it defaults to the length of the list. If step is omitted, it defaults to 1.
1
x = ["A", "B", "C", "D"]
2
3
print(x[:2]) #["A", "B"]
4
print(x[1:]) #["B", "C", "D"]
5
print(x[:]) #["A", "B", "C", "D"]
6
print(x[-1::]) #["D"]
7
print(x[:-1:]) #["A", "B", "C"]
Tip
Slicing creates a new list, so modifying a slice doesn’t affect the original list unless you assign it back.
To remove elements from a list, the methods pop(), remove(), and clear() can be used.
pop() removes and returns the element at a specific index. If no index is specified, it removes and returns the last element. If there is no element at the specified index or the list is empty, it raises an IndexError.
remove() removes the first occurrence of a specified value. If the value doesn’t exist in the list, it raises a ValueError.
clear() removes all elements from the list, making it empty.
Another way to iterate through a list is using a while loop:
1
fruits = ["apple", "banana", "orange"]
2
i =0
3
4
while i <len(fruits):
5
print(fruits[i])
6
i +=1
Tip
for loops are generally preferred for iterating through lists as they are more readable and less error-prone. while loops are generally used when the number of iterations is unknown or when the loop needs to be terminated by a condition other than the number of iterations.
When we usually write x = y, we are binding the value of y to the variable x. Since every value in Python is basically an object, then knowing the mutability of y (if y is mutable or immutable) is important. If y is a mutable object, then both x and y will be able to change it (which may not be desirable). Consider the following example:
assignment-immutable-example.py
1
x =3
2
y = x
3
x +=1
4
y -=1
5
print(x) #4
6
print(y) #2
Since x and y are both integers, which are immutable, then x and y will changeindependently. Another example:
assignment-mutable-example.py
1
x = [1, 2, 3]
2
y = x
3
x.append(4)
4
print(x) # [1, 2, 3, 4]
5
print(y) # [1, 2, 3, 4]
Here we were intending on copying the list so that each variable would have its own copy of the list. Since x and y are both lists, which are mutable, then x and y will changetogether. This is not what we intended, so we need to use a different approach.
The identity operator is and is not are used to check if two variables refer to the same object in memory.
1
x = [1, 2, 3]
2
y = [1, 2, 3]
3
print(x == y) # True
4
print(x is y) # False
1
x = [1, 2, 3]
2
y = x
3
print(x == y) # True
4
print(x is y) # True
5
print(x isnot y) # False
Note
The identity operator is is different from the equality operator ==. The equality operator == checks if two objects have the same value, while the identity operator is checks if two variables refer to the same object in memory.
Tip
For lists, use == to compare values and is to check if two variables point to the same list object. For immutable types like integers and strings, Python may reuse objects, so is might work, but it’s still better to use == for value comparison.
Exercise 1: What is the output of the following code
What is the output of the following code:
1
k = [1, 2, 3, 4, 5, 6]
2
for i inrange(len(k)):
3
if i in k:
4
print(i, end=" ")
Answer:
The output is: 1 2 3 4 5
The loop iterates through indices 0, 1, 2, 3, 4, 5 (from range(len(k))). For each index i, it checks if i in k. Since k = [1, 2, 3, 4, 5, 6], the values 1, 2, 3, 4, 5 are in the list, but 0 and 6 are not.
Exercise 2: How to access the number 8 from this list
How to access the number 8 from this list: [[1, 2, 3], [[4, 5, 6], [7, [8, 9]]]]
Answer:
The number 8 can be accessed using nested indexing:
1
my_list = [[1, 2, 3], [[4, 5, 6], [7, [8, 9]]]]
2
print(my_list[1][1][1][0]) # Output: 8
Breaking it down:
my_list[1] accesses the second element: [[4, 5, 6], [7, [8, 9]]]
my_list[1][1] accesses the second element of that: [7, [8, 9]]
my_list[1][1][1] accesses the second element of that: [8, 9]
my_list[1][1][1][0] accesses the first element of that: 8
Exercise 3: Printing a list to the console
Write a program that creates a list [1, 2, 3, 4, 5] and prints it to the console.
Print List
Answer:
1
my_list = [1, 2, 3, 4, 5]
2
print(my_list)
Exercise 4: Find the sum of the elements in a list
Write a program that reads the size of the list followed by the elements of the list and prints the sum of all elements in the list.
Sum of List Elements
Answer:
1
size =int(input())
2
numbers = []
3
for i inrange(size):
4
numbers.append(int(input()))
5
total =0
6
for num in numbers:
7
total += num
8
print(total)
or
1
size =int(input())
2
numbers = []
3
for i inrange(size):
4
numbers.append(int(input()))
5
print(sum(numbers))
Exercise 5: Reading from the user a list of positive numbers
Write a program that reads the size of the list followed by numbers, then only adds the positive numbers to the list and prints it.
Read Positive Numbers
Answer:
1
size =int(input())
2
numbers = []
3
for i inrange(size):
4
num =int(input())
5
if num >=0:
6
numbers.append(num)
7
print(numbers)
Exercise 6: Finding the minimum value in a list without the min function
Write a program that reads the size of the list followed by the elements of the list and finds the minimum value without using the min() function.
Find Minimum
Answer:
1
size =int(input())
2
numbers = []
3
for i inrange(size):
4
numbers.append(int(input()))
5
minimum = numbers[0]
6
for num in numbers:
7
if num < minimum:
8
minimum = num
9
print(minimum)
Exercise 7: Check if an element is in the list without the in operator
Write a program that reads the size of the list followed by the elements of the list, then reads a target number, and checks if the target number exists in the list without using the in operator. Print "Found" if it exists, otherwise print "Not Found".
Check Membership
Answer:
1
size =int(input())
2
numbers = []
3
for i inrange(size):
4
numbers.append(int(input()))
5
target =int(input())
6
found =False
7
for num in numbers:
8
if num == target:
9
found =True
10
break
11
if found:
12
print("Found")
13
else:
14
print("Not Found")
Or we could use the else keyword to our advantage:
1
size =int(input())
2
numbers = []
3
for i inrange(size):
4
numbers.append(int(input()))
5
target =int(input())
6
for num in numbers:
7
if num == target:
8
print("Found")
9
break
10
else:
11
print("Not Found")
Exercise 8: Find all duplicate elements inside a list
Write a program that reads the size of the list followed by the elements of the list and prints all duplicate elements (each duplicate printed only once, in the order they first appear).
Find Duplicates
Answer:
1
size =int(input())
2
numbers = []
3
for i inrange(size):
4
numbers.append(int(input()))
5
duplicates = []
6
seen = []
7
for num in numbers:
8
if num in seen and num notin duplicates:
9
duplicates.append(num)
10
seen.append(num)
11
for dup in duplicates:
12
print(dup)
Exercise 9: Split a list into two lists, one with the even numbers and one with the odd numbers
Write a program that reads the size of the list followed by the elements of the list and splits them into two lists: one containing all even numbers and one containing all odd numbers. Print both lists on separate lines.
Split Even and Odd
Answer:
1
size =int(input())
2
numbers = []
3
for i inrange(size):
4
numbers.append(int(input()))
5
even = []
6
odd = []
7
for num in numbers:
8
if num %2==0:
9
even.append(num)
10
else:
11
odd.append(num)
12
print(even)
13
print(odd)
Exercise 10: Reverse a list using a loop
Write a program that reads the size of the list followed by the elements of the list and reverses the list using a loop (without using the reverse() method or slicing). Print the reversed list.
Reverse List
Answer:
1
size =int(input())
2
numbers = []
3
for i inrange(size):
4
numbers.append(int(input()))
5
reversed_list = []
6
for i inrange(len(numbers) -1, -1, -1):
7
reversed_list.append(numbers[i])
8
print(reversed_list)
Exercise 11: Sum of all inner lists
Given a list of lists, where each list contains numbers, write a program which reads the number of inner lists, then for each inner list reads the size of that inner list followed by its elements, and prints the sum of all the inner lists (each sum on a new line).