A list in Python is a data structure that is used to store a sequence of objects. Some examples are given below:
xxxxxxxxxx
31numbers = [1, 2, 3, 4, 5]
2letters = ['a', 'b', 'c', 'd']
3words = ['this', 'is', 'a', 'list']
print(numbers)
will give the following output:xxxxxxxxxx
11[1, 2, 3, 4, 5]
xxxxxxxxxx
11mixture = [1, 1.0, '1', True]
list
. We can also check if a given variable holds an object of type list
:xxxxxxxxxx
31numbers = [1, 2, 3]
2print(type(numbers))
3print(isinstance(numbers, list))
len
function can be used to find the number of elements in a list:xxxxxxxxxx
21numbers = [1, 2, 3]
2print(f'This list has {len(numbers)} elements in it')
xxxxxxxxxx
41numbers = [1, 2, 3, 4]
2print(numbers[0], numbers[1], numbers[2], numbers[3])
3print(numbers[1 : 3])
4print(numbers[-2])
As a list is a sequence, we can iterate through it using for
. This is one of the primary uses of the for
loop:
xxxxxxxxxx
41# Method-1
2numbers = [1, 2, 3, 4]
3for num in numbers:
4 print(num)
The loop variable — num
— picks one item at a time from the sequence. In the body of the loop, we are just printing this item. We can rewrite the code given above using a while
loop:
xxxxxxxxxx
61# Method-2
2numbers = [1, 2, 3, 4]
3index = 0
4while index < len(numbers):
5 print(numbers[index])
6 index += 1
Finally, we can also use the for
loop to iterate through the indices of the list. For this, we take the help of the range
function.
xxxxxxxxxx
41# Method-3
2numbers = [1, 2, 3, 4]
3for index in range(len(numbers)):
4 print(numbers[index])
In the example given above, len(numbers)
is equal to 4
. So, the range
sequence will be 0, 1, 2, 3
. index
is the loop variable that iterates through this sequence.
Methods 2 and 3 are very similar. Both iterate through the sequence of indices, and use list indexing to access the corresponding element in the list. The only difference is that method-2 uses while
, while method-3 uses for
. Method-1 stands out from the other two as it directly pulls elements from the sequence.
Lists are typically used in problems where we wish to store a collection of items. Usually, we start with an empty list. Python provides two ways to create an empty list:
xxxxxxxxxx
21list1 = []
2list2 = list()
Both list1
and list2
are empty lists. The interpreter doesn't mind spaces between the opening and closing braces, so list1 = [ ]
also works. Given an empty list, how do we add items to it? Python provides two ways to do this:
xxxxxxxxxx
41list1 = list1 + [1]
2print(list1)
3list2 = list2.append(1)
4print(list2)
Both lists end up having just the one element. The first method is called list concatenation, i.e., two lists are being concatenated or combined together. Treat concatenation like joining two compartments of a train together. It is very similar to string concatenation. The second way uses a method called append
that is essentially a function defined for the list
type. Append adds elements at the end of the list.
Consider the following problem:
Generate the list of positive integers less than 100 that are divisible by 3.
There are at least two ways of doing this. The first one uses while
:
xxxxxxxxxx
61# Method-1
2num = 3
3nums_div = []
4while num < 100:
5 nums_div.append(num)
6 num += 3
The next method uses for
:
xxxxxxxxxx
41# Method-2
2nums_div = []
3for num in range(3, 100, 3):
4 nums_div.append(num)
We have already seen how the +
operator works with lists:
xxxxxxxxxx
61list1 = [1, 2, 3]
2list2 = [4, 5, 6]
3list12 = list1 + list2
4print(list12)
5list21 = list2 + list1
6print(list21)
This gives the concatenated output:
xxxxxxxxxx
21[1, 2, 3, 4, 5, 6]
2[4, 5, 6, 1, 2, 3]
The order matters when two lists are being concatenated! The next is the *
operator:
xxxxxxxxxx
41list1 = [0] * 5
2print(list1)
3list2 = [1, 2, 3] * 3
4print(list2)
This replicates the list. The following is the output:
xxxxxxxxxx
21[0, 0, 0, 0, 0]
2[1, 2, 3, 1, 2, 3, 1, 2, 3]
Two lists are equal if they have the same sequence of elements:
xxxxxxxxxx
51l1 = [1, 2, 3]
2l2 = [1, 2, 3]
3l3 = [3, 2, 1]
4print(l1 == l2)
5print(l2 == l3)
This results in:
xxxxxxxxxx
21True
2False
Finally, two lists can be compared with the >
or the <
operator. List comparison works very similar to string comparison, in that it uses lexicographic ordering. We looked at this in the first chapter:
Lexicographic ordering
First element from both lists are compared. If they differ this determines the outcome of the comparison. If they are equal, then the second element of both the lists are compared. This process continues until either list is exhausted.
Some example comparisons:
xxxxxxxxxx
41print([1, 2] < [2, 1])
2print([1] < [1, 2, 3])
3print([2, 3, 4] < [3])
4print([] < [1])
All four of them result in True
.
Let us look at some built-in functions that operate on lists:
sum
: this is used to find the sum of the elements in a list of numbers:xxxxxxxxxx
21a = [1, 2, 3]
2print(sum(a))
max
and min
: these two functions find the maximum and minimum value in a list respectively.xxxxxxxxxx
21a = [1, 2, 3]
2print(min(a), max(a))
What happens if a
is a list of strings? What would max(a)
and min(a)
produce?
sorted
: this function returns a sorted listxxxxxxxxxx
21a = [2, 1, 3]
2print(sorted(a))
We have come across the range
object and seen how useful it was in iterating through a sequence. So far range
has been associated with the for
loop. Its time has come to break out of the loopy prison:
xxxxxxxxxx
21numbers = range(10)
2print(numbers)
This gives range(0, 10)
as an output. This is a sequence that we can iterate over. Python provides a way of turning this object into a list:
xxxxxxxxxx
21numbers = list(range(10))
2print(numbers)
This gives [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
as the output.