1. The list is a type of data in Python used to store multiple objects. It is an ordered and mutable collection of comma-separated items between square brackets, e.g.:
1 |
my_list = [1, None, True, "I am a string", 256, 0] |
2. Lists can be indexed and updated, e.g.:
1 2 3 4 5 6 7 8 9 10 |
my_list = [1, None, True, 'I am a string', 256, 0] print(my_list[3]) # outputs: I am a string print(my_list[-1]) # outputs: 0 my_list[1] = '?' print(my_list) # outputs: [1, '?', True, 'I am a string', 256, 0] my_list.insert(0, "first") my_list.append("last") print(my_list) # outputs: ['first', 1, '?', True, 'I am a string', 256, 0, 'last'] |
3. Lists can be nested, e.g.:
1 |
my_list = [1, 'a', ["list", 64, [0, 1], False]] |
4. List elements and lists can be deleted, e.g.:
1 2 3 4 5 |
my_list = [1, 2, 3, 4] del my_list[2] print(my_list) # outputs: [1, 2, 4] del my_list # deletes the whole list |
5. Lists can be iterated through using the for
loop, e.g.:
1 2 3 4 |
my_list = ["white", "purple", "blue", "yellow", "green"] for color in my_list: print(color) |
6. The len()
function may be used to check the list’s length, e.g.:
1 2 3 4 5 |
my_list = ["white", "purple", "blue", "yellow", "green"] print(len(my_list)) # outputs 5 del my_list[2] print(len(my_list)) # outputs 4 |
7. A typical function invocation looks as follows: result = function(arg)
, while a typical method invocation looks like this:result = data.method(arg)
.
8. You can use the sort() method to sort elements of a list, e.g.:
1 2 3 4 5 |
lst = [5, 3, 1, 2, 4] print(lst) lst.sort() print(lst) # outputs: [1, 2, 3, 4, 5] |
- Both
sort()
andsorted()
sort a list in ascending order. sort()
is a method andsorted()
is a built-in function.sort()
changes the list in place, whilesorted()
creates a new listsort()
is defined only for lists, whilesorted()
accepts any iterable (such as strings and tuples)
9. There is also a list method called reverse(), which you can use to reverse the list, e.g.:
1 2 3 4 5 |
lst = [5, 3, 1, 2, 4] print(lst) lst.reverse() print(lst) # outputs: [4, 2, 1, 3, 5] |
or
1 2 |
lst = [2, 3, 7, 11, 26] print(lst[::-1]) # outputs: [26, 11, 7, 3, 2] |
In Python, the slice notation [::-1]
returns the elements of a data collection, such as a list, in reverse order.
10. If you have a list list1
, then the following assignment: list2 = list1
does not make a copy of the list1
list, but makes the variables list1
and list2
point to one and the same list in memory. For example:
1 2 3 4 5 6 |
vehicles_one = ['car', 'bicycle', 'motor'] print(vehicles_one) # outputs: ['car', 'bicycle', 'motor'] vehicles_two = vehicles_one del vehicles_one[0] # deletes 'car' print(vehicles_two) # outputs: ['bicycle', 'motor'] |
11. If you want to copy a list or part of the list, you can do it by performing slicing:
1 2 3 4 |
colors = ['red', 'green', 'orange'] copy_whole_colors = colors[:] # copy the entire list copy_part_colors = colors[0:2] # copy part of the list |
12. You can use negative indices to perform slices, too. For example:
1 2 3 |
sample_list = ["A", "B", "C", "D", "E"] new_list = sample_list[2:-1] print(new_list) # outputs: ['C', 'D'] |
13. The start
and end
parameters are optional when performing a slice: list[start:end]
, e.g.:
1 2 3 4 5 6 7 8 |
my_list = [1, 2, 3, 4, 5] slice_one = my_list[2: ] slice_two = my_list[ :2] slice_three = my_list[-2: ] print(slice_one) # outputs: [3, 4, 5] print(slice_two) # outputs: [1, 2] print(slice_three) # outputs: [4, 5] |
14. You can delete slices using the del
instruction:
1 2 3 4 5 6 |
my_list = [1, 2, 3, 4, 5] del my_list[0:2] print(my_list) # outputs: [3, 4, 5] del my_list[:] print(my_list) # deletes the list content, outputs: [] |
15. You can test if some items exist in a list or not using the keywords in
and not in
, e.g.:
1 2 3 4 5 |
my_list = ["A", "B", 1, 2] print("A" in my_list) # outputs: True print("C" not in my_list) # outputs: True print(2 not in my_list) # outputs: False |
16. List comprehension allows you to create new lists from existing ones in a concise and elegant way. The syntax of a list comprehension looks as follows:
1 |
[expression for element in list if conditional] |
which is actually an equivalent of the following code:
1 2 3 |
for element in list: if conditional: expression |
Let’s assume that we’re able to use the selected numbers to represent any chess piece. We can also assume that every row on the chessboard is a list.
Look at the code below:
1 2 3 |
row = [] for i in range(8): row.append(WHITE_PAWN) |
It builds a list containing eight elements representing the second row of the chessboard – the one filled with pawns (assume that WHITE_PAWN is a predefined symbol representing a white pawn).
The same effect may be achieved by means of a list comprehension, the special syntax used by Python in order to fill massive lists.
1 |
row = [WHITE_PAWN for i in range(8)] |
The part of the code placed inside the brackets specifies:
the data to be used to fill the list (WHITE_PAWN)
the clause specifying how many times the data occurs inside the list (for i in range(8))
Here’s an example of a list comprehension ‒ the code creates a five-element list filled with the first five natural numbers raised to the power of 3:
1 2 |
cubed = [num ** 3 for num in range(5)] print(cubed) # outputs: [0, 1, 8, 27, 64] |
17. Swapping the lists’s elements.
you can easily swap the list’s elements to reverse their order:
1 2 3 4 5 |
my_list = [10, 1, 8, 3, 5] my_list[0], my_list[4] = my_list[4], my_list[0] my_list[1], my_list[3] = my_list[3], my_list[1] print(my_list) |
Run the snippet. Its output should look like this:
[5, 3, 8, 1, 10]
Will it still be acceptable with a list containing 100 elements? No, it won’t. You use the for
loop to do the same thing automatically, irrespective of the list’s length.
This is how we’ve done it:
1 2 3 4 5 |
my_list = [10, 1, 8, 3, 5] length = len(my_list) for i in range(length // 2): my_list[i], my_list[length - i - 1] = my_list[length - i - 1], my_list[i] print(my_list) |
Example #1:
1 |
squares = [x ** 2 for x in range(10)] |
The snippet produces a ten-element list filled with squares of ten integer numbers starting from zero (0, 1, 4, 9, 16, 25, 36, 49, 64, 81)
Example #2:
1 |
twos = [2 ** i for i in range(8)] |
The snippet creates an eight-element array containing the first eight powers of two (1, 2, 4, 8, 16, 32, 64, 128)
Example #3:
1 |
odds = [x for x in squares if x % 2 != 0 ] |
The snippet makes a list with only the odd elements of the
squares
list.
1 2 3 4 5 6 7 8 9 |
# A four-column/four-row table ‒ a two dimensional array (4x4) table = [[":(", ":)", ":(", ":)"], [":)", ":(", ":)", ":)"], [":(", ":)", ":)", ":("], [":)", ":)", ":)", ":("]] print(table) print(table[0][0]) # outputs: ':(' print(table[0][3]) # outputs: ':)' |
18. You can nest as many lists in lists as you want, thereby creating n-dimensional lists, e.g., three-, four- or even sixty-four-dimensional arrays. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Cube - a three-dimensional array (3x3x3) cube = [[[':(', 'x', 'x'], [':)', 'x', 'x'], [':(', 'x', 'x']], [[':)', 'x', 'x'], [':(', 'x', 'x'], [':)', 'x', 'x']], [[':(', 'x', 'x'], [':)', 'x', 'x'], [':)', 'x', 'x']]] print(cube) print(cube[0][0][0]) # outputs: ':(' print(cube[2][2][0]) # outputs: ':)' |
What is the output of the following snippet?
1 2 3 4 5 6 7 8 |
lst = [1, 2, 3, 4, 5] lst.insert(1, 6) del lst[0] lst.append(1) print(lst) # Output: [6, 2, 3, 4, 5, 1] |
Exercise 2
What is the output of the following snippet?
1 2 3 4 5 6 7 8 9 10 11 |
lst = [1, 2, 3, 4, 5] lst_2 = [] add = 0 for number in lst: add += number lst_2.append(add) print(lst_2) # Output: [1, 3, 6, 10, 15] |
Exercise 3
What happens when you run the following snippet?
1 2 3 4 5 |
lst = [] del lst print(lst) # Output: NameError: name 'lst' is not defined<code class="codep "> |
Exercise 4
What is the output of the following snippet?
1 2 3 4 5 6 7 |
lst = [1, [2, 3], 4] print(lst[1]) print(len(lst)) # Output: # [2, 3] # 3<code class="codep "> |
Exercise 5
What is the output of the following snippet?
1 2 3 4 5 6 7 8 9 |
list_1 = ["A", "B", "C"] list_2 = list_1 list_3 = list_2 del list_1[0] del list_2[0] print(list_3) # Output: ['C'] |
Exercise 6
What is the output of the following snippet?
1 2 3 4 5 6 7 8 9 |
list_1 = ["A", "B", "C"] list_2 = list_1 list_3 = list_2 del list_1[0] del list_2 print(list_3) ['B', 'C'] |
Exercise 7
What is the output of the following snippet?
1 2 3 4 5 6 7 8 9 10 |
list_1 = ["A", "B", "C"] list_2 = list_1 list_3 = list_2 del list_1[0] del list_2[:] print(list_3) [] |
Exercise 8
What is the output of the following snippet?
1 2 3 4 5 6 7 8 9 10 |
list_1 = ["A", "B", "C"] list_2 = list_1[:] list_3 = list_2[:] del list_1[0] del list_2[0] print(list_3) ['A', 'B', 'C'] |
Exercise 9
Insert in or not in instead of ??? so that the code outputs the expected result.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
my_list = [1, 2, "in", True, "ABC"] print(1 ??? my_list) # outputs True print("A" ??? my_list) # outputs True print(3 ??? my_list) # outputs True print(False ??? my_list) # outputs False my_list = [1, 2, "in", True, "ABC"] print(1 in my_list) # outputs True print("A" not in my_list) # outputs True print(3 not in my_list) # outputs True print(False in my_list) # outputs False |
Exercise 10
What is the output of the following snippet?
1 2 3 4 |
lst = ["D", "F", "A", "Z"] lst.sort() print(lst) |
['A', 'D', 'F', 'Z']
Exercise 11
What is the output of the following snippet?
1 2 3 4 5 6 7 8 |
a = 3 b = 1 c = 2 lst = [a, c, b] lst.sort() print(lst) |
[1, 2, 3]
Exercise 12
What is the output of the following snippet?
1 2 3 4 5 6 7 8 9 |
a = "A" b = "B" c = "C" d = " " lst = [a, b, c, d] lst.reverse() print(lst) |
[' ', 'C', 'B', 'A']
Ex. 13
What is the output of the following code snippet?
1 2 3 4 5 6 |
d1 = {1: 'one', 2: 'two', 3: 'three'} d2 = d1 del d1 print(d2) |
{1: 'one', 2: 'two', 3: 'three'}
- After line 3 of the code,
d1
andd2
refer to the same dictionary. In other words,d1
andd2
are two variables that point to the same dictionary in memory and not two separate copies of it.
- The instruction in line 4 removes the reference
d1
, but the variabled2
will continue to point to the starting dictionary. Therefore, in line 6, theprint()
function will print the entire dictionary.
Ex. 14
What is the output of the following code snippet?
1 2 3 4 5 |
lst = [3, 2, 0, 4] for n in lst: if n != 2 and n != 4: print(lst[n], end=" ") |
4 3
- The program executes the
for
loop4
times, according to the four elements of thelst
list. Due to theif
condition, the program will execute theprint
statement only for the values3
and0
in the list. - In the
print
statement,n
is used as an index to get the corresponding value inlst
. - Due to the presence of the
end=" "
parameter the numbers are printed on a single line separated by a space. - Here’s how the for loop works:
- First iteration:
n = 3
.
Theif
condition isTrue
because3
is different from2
and4
.
Theprint
statement outputs4
to the screen:print(lst[3], end=" ")
->print(4, end=" ")
->4
.(The list index starts with0
). - Second iteration:
n = 2
.
Theif
condition isFalse
. - Third iteration:
n = 3
.
Theif
condition isTrue
because0
is different from2
and4
.
Theprint
statement outputs3
to the screen:print(lst[0], end=" ")
->print(3, end=" ")
->3
. - Fourth iteration:
n = 4
.
Theif
condition isFalse
and the program ends.
- First iteration:
Ex.15
What is the output of the following code snippet?
1 2 3 |
lst = ['a', 'C', " ", 'b', 'Z'] lst.sort() print(lst) |
Ex. 16
What is the output of the following code snippet?
1 2 3 4 5 6 7 |
lst = [1, 2, 3, 4, 5] lst.append([6, 7]) lst.extend(['a', 'b']) lst.pop() print(lst) |
Ex.17
What is the output of the following code snippet?
1 2 3 4 |
str = """ Python""" print(len(str)) |
Ex. 18
What is the output of the following code snippet?
1 |
print(list(range(-3))) |
Ex. 19
What is the output of the following code snippet?
1 2 3 4 5 6 7 |
def fun(): lst[0] = 8 lst = [3, 7, 1, 5, 9] fun() print(lst) |
Ex. 20
What is the output of the following code snippet?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
l3d = [[['A','B','C'], ['X','Y','Z'], ['J','K','L']], [[100,200,300], [400,500,600], [700,800,900]], [['@','$','§'], ['?','#','&'], ['*','!','=']]] print(l3d[2][1]) print(l3d[2][1][1]) |
Scenario
Imagine a list – not very long, not very complicated, just a simple list containing some integer numbers. Some of these numbers may be repeated, and this is the clue. We don’t want any repetitions. We want them to be removed.
Your task is to write a program which removes all the number repetitions from the list. The goal is to have a list in which all the numbers appear not more than once.
Note: assume that the source list is hard-coded inside the code – you don’t have to enter it from the keyboard. Of course, you can improve the code and add a part that can carry out a conversation with the user and obtain all the data from her/him.
Hint: we encourage you to create a new list as a temporary work area – you don’t need to update the list in situ.
1 2 3 4 5 6 7 8 9 |
my_list = [1, 2, 4, 4, 1, 4, 2, 6, 2, 9] new_list = [] for number in my_list: if number not in new_list: new_list.append(number) print("The list with unique elements only:") print(new_list) |