Module 1, topic 4, week 2, Thursday
Data structures: lists and tuples
Lists and their methods, loops over lists, tuples, reading input with map, and map and filter
Lesson notebook
The lesson as a Jupyter notebook: the explanations, every example and the 26 solved problems, ready to run and change.
topic-04-lists-and-tuples.ipynb, 103 KB
Practice notebook
The 15 practice problems with examples of input and output, a hint and a hidden solution for each.
topic-04-practice.ipynb, 27 KB
Introduction: lists and tuples
A beginner-friendly guide to the first two data structures of Python: lists and tuples. It starts from the simplest examples and gets harder step by step. It shows every everyday method (append, extend, insert, remove, pop, del, sort and more), how to use operators, if/else, for and while with lists and tuples, how to read a whole list from the user in one line with map, and how map and filter work and differ. Then it walks through 26 solved problems from easy to medium-hard. At the end there are practice problems.
You should already know variables, data types, operators, if/else, loops and functions.
What you will learn
- 1.How
mapreads several values in one line:a, b = map(int, input().split()) - 2.What a list is, and how to create, read, change, grow, shrink, search, sort and copy one
- 3.Every common list method and when to use it
- 4.Operators,
if/else,forandwhileapplied to lists - 5.How to read a whole list from the user:
numbers = list(map(int, input().split())) - 6.What a tuple is, how it differs from a list, and when to use each
- 7.
mapandfilter: what each one does, their differences, and which problems each one solves - 8.26 solved problems and practice problems
1Reading several values in one line with map
Until now we read one value per line:
a = int(input())
b = int(input())
print(a + b)Output
5 7 12
(In this guide, when a program reads input, the output block shows what the user typed first: here 5 and 7.)
The user had to press Enter after each number. Very often the numbers come on one line, separated by spaces, like 5 7. To read them we need three small steps. Let us look at each step alone.
1.1Step 1: input() gives one text
line = input()
print(line)
print(type(line))Output
5 7 5 7 <class 'str'>
Change it and run: type three numbers in the input box. type(line) is still str.
input() always gives text. Here the text is "5 7": one string, not two numbers.
1.2Step 2: .split() cuts the text into pieces
line = "5 7"
parts = line.split()
print(parts)Output
['5', '7']
Change it and run: put three numbers in the text: "5 7 9". How many pieces are there now?
.split() cuts the text at the spaces and gives the pieces back in square brackets. This is a list (the main topic of this lesson). Notice the quotes: the pieces are still text, '5' and '7'.
1.3Step 3: map(int, ...) converts every piece
We need to run int() on every piece. That is exactly what map does:
map(function, sequence)
map takes a function and a sequence, and applies the function to every item of the sequence.
parts = ["5", "7"]
numbers = map(int, parts)
a, b = numbers
print(a, b)
print(a + b)Output
5 7 12
Change it and run: change int to float. What do a and b look like now?
map(int, parts) means: "run int on '5', then run int on '7'". The line a, b = numbers puts the first result into a and the second into b.
Notice: we write int, not int(). We give map the function itself. map is the one that calls it, once for every item.
1.4All three steps in one line
a, b = map(int, input().split())
print(a + b)Output
5 7 12
Change it and run: type 10 25 in the input box. Then type only one number and read the error.
Read it from the inside out:
| Piece | What it does | Result for the input 5 7 |
|---|---|---|
input() | reads the line as text | "5 7" |
.split() | cuts the text at the spaces | ['5', '7'] |
map(int, ...) | runs int on every piece | 5 and 7 |
a, b = ... | stores the results in two variables | a is 5, b is 7 |
input()
"5 7"
one text
.split()
['5', '7']
a list of texts
map(int, ...)
5 7
two numbers
a, b = ...
a = 5 b = 7
two variables
a, b = map(int, input().split()) does these four steps, from the inside out.1.5The same idea with other types and more values
a, b, c = map(int, input().split())
print(a + b + c)Output
3 10 4 17
width, height = map(float, input().split())
print(width * height)Output
2.5 4 10.0
Change it and run: type 3 4. The result is still a decimal number, because of float.
For text you do not need map, because .split() already gives text:
first_name, last_name = input().split()
print("Hello,", first_name, last_name)Output
Aylin Demir Hello, Aylin Demir
1.6The number of variables must match
If the user types 3 values but you wrote 2 variables, Python stops with an error:
a, b = map(int, input().split())Output
5 7 9
Error
ValueError: too many values to unpack (expected 2)
And with too few values:
a, b = map(int, input().split())Output
5
Error
ValueError: not enough values to unpack (expected 2, got 1)
What if we do not know how many numbers the user will type? Then we cannot write a variable for each one. We need one variable that holds many values. That is a list. We come back to map in Part 6 (reading a whole list) and in Part 8 (map in detail).
Try it yourself
Show a hint
width, height = map(int, input().split()) reads both numbers. Then multiply them.Show the solution
width, height = map(int, input().split())
print(width * height)Output
12
2Lists: creating, reading and changing
2.1What is a list?
Imagine you must store the grades of 5 students. Without a list:
grade1 = 85
grade2 = 92
grade3 = 78
grade4 = 60
grade5 = 95Now imagine 500 students. A list stores many values in one variable, in order:
grades = [85, 92, 78, 60, 95]
print(grades)Output
[85, 92, 78, 60, 95]
Real-life picture: a list is a row of numbered boxes, or a shopping list where you can add items, cross items out, and change them.
2.2Creating lists
A list is written in square brackets, with commas between the items:
numbers = [10, 20, 30]
names = ["Aylin", "Murad", "Leyla"]
prices = [2.5, 10.0, 7.25]
empty = []
mixed = [1, "two", 3.0, True]
print(numbers)
print(names)
print(prices)
print(empty)
print(mixed)
print(type(numbers))Output
[10, 20, 30] ['Aylin', 'Murad', 'Leyla'] [2.5, 10.0, 7.25] [] [1, 'two', 3.0, True] <class 'list'>
Change it and run: add one more name to names.
- A list can hold any type, even different types together (but usually all items have the same type).
- A list can be empty:
[]. - The same value can appear more than once:
[1, 1, 2].
2.3How many items? len()
grades = [85, 92, 78, 60, 95]
print(len(grades))
print(len([]))Output
5 0
Change it and run: add a grade to the list. len grows by one.
2.4Making a list from something else: list()
print(list("Python"))
print(list(range(5)))
print(list(range(1, 11, 2)))Output
['P', 'y', 't', 'h', 'o', 'n'] [0, 1, 2, 3, 4] [1, 3, 5, 7, 9]
Change it and run: change "Python" to your name.
list() turns a text into a list of characters, and a range into a list of numbers.
2.5Indexes
Every item has a position number called an index. Counting starts at 0.
| index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| item | "a" | "b" | "c" | "d" | "e" |
| negative | -5 | -4 | -3 | -2 | -1 |
letters[-1] is always the last item.letters = ["a", "b", "c", "d", "e"]
print(letters[0])
print(letters[1])
print(letters[4])Output
a b e
Change it and run: print letters[2].
Negative indexes count from the end. -1 is the last item:
letters = ["a", "b", "c", "d", "e"]
print(letters[-1])
print(letters[-2])Output
e d
Change it and run: print letters[-5]. Which item is it?
The last item is always letters[-1] or letters[len(letters) - 1].
An index that does not exist gives an error:
letters = ["a", "b", "c", "d", "e"]
print(letters[5])Error
IndexError: list index out of range
2.6Slices: taking a part of a list
list[start:stop] gives a new list from index start up to, but not including, stop (the same rule as range).
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4])
print(numbers[:3])
print(numbers[3:])
print(numbers[-2:])
print(numbers[:])Output
[20, 30, 40] [10, 20, 30] [40, 50, 60] [50, 60] [10, 20, 30, 40, 50, 60]
Change it and run: print numbers[2:5]. Predict the result first.
| Slice | Meaning |
|---|---|
numbers[1:4] | indexes 1, 2, 3 |
numbers[:3] | the first 3 items |
numbers[3:] | from index 3 to the end |
numbers[-2:] | the last 2 items |
numbers[:] | the whole list (a copy) |
A third number is the step:
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[::2])
print(numbers[1::2])
print(numbers[::-1])Output
[10, 30, 50] [20, 40, 60] [60, 50, 40, 30, 20, 10]
Change it and run: print numbers[::3].
numbers[::-1] gives the list reversed.
Slices never give an error, even when the numbers are too big:
numbers = [10, 20, 30]
print(numbers[1:100])
print(numbers[5:])Output
[20, 30] []
Choose a slice and see which items it takes.
numbers = [10, 20, 30, 40, 50, 60] print(numbers[1:4])
| 0 | 1 | 2 | 3 | 4 | 5 |
| 10 | 20 | 30 | 40 | 50 | 60 |
| -6 | -5 | -4 | -3 | -2 | -1 |
Result: [20, 30, 40]
The item at the stop index is never taken. An empty place means "from the start" or "to the end", and with a negative step the slice walks backwards.
2.7Lists can be changed (they are mutable)
A text cannot be changed in place, but a list can. This is the most important property of a list. The word for it is mutable (changeable).
grades = [85, 92, 78]
grades[0] = 90
print(grades)
grades[-1] = grades[-1] + 5
print(grades)Output
[90, 92, 78] [90, 92, 83]
Change it and run: change the second grade to 100.
You can even replace a whole slice:
numbers = [1, 2, 3, 4, 5]
numbers[1:3] = [20, 30]
print(numbers)Output
[1, 20, 30, 4, 5]
Change it and run: replace the slice with three items: [20, 30, 40]. The list gets longer.
Compare with text, which cannot be changed like this:
word = "cat"
word[0] = "b"Error
TypeError: 'str' object does not support item assignment
Changing an index that does not exist is also an error. You cannot add a new item this way:
grades = [85, 92, 78]
grades[3] = 100Error
IndexError: list assignment index out of range
To add items we use methods. A method is a function that belongs to a value, and is called with a dot: list_name.method().
Try it yourself
days, print: the first day, the last day, the working days (the first five), the weekend (the last two), and every second day starting with Monday. Use indexes and slices only.Show a hint
days[0], days[-1], then three slices: [:5], [-2:] and [::2].Show the solution
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
print(days[0])
print(days[-1])
print(days[:5])
print(days[-2:])
print(days[::2])Output
Mon Sun ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] ['Sat', 'Sun'] ['Mon', 'Wed', 'Fri', 'Sun']
3Adding and removing items
3.1append(item): add one item at the end
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)
fruits.append("orange")
print(fruits)Output
['apple', 'banana', 'cherry'] ['apple', 'banana', 'cherry', 'orange']
Change it and run: append your favourite fruit.
append is the most used list method. A very common pattern is to start with an empty list and fill it in a loop:
squares = []
for number in range(1, 6):
squares.append(number * number)
print(squares)Output
[1, 4, 9, 16, 25]
Change it and run: change number * number to number * 2.
3.2insert(index, item): add one item at a position
fruits = ["apple", "banana", "cherry"]
fruits.insert(1, "kiwi")
print(fruits)
fruits.insert(0, "mango")
print(fruits)Output
['apple', 'kiwi', 'banana', 'cherry'] ['mango', 'apple', 'kiwi', 'banana', 'cherry']
Change it and run: insert "pear" at index 2.
The new item takes the given index, and everything after it moves one place to the right.
3.3extend(other_list): add all items of another list
fruits = ["apple", "banana"]
fruits.extend(["cherry", "orange"])
print(fruits)Output
['apple', 'banana', 'cherry', 'orange']
3.4append vs extend (a classic confusion)
a = [1, 2]
a.append([3, 4])
print(a)
print(len(a))
b = [1, 2]
b.extend([3, 4])
print(b)
print(len(b))Output
[1, 2, [3, 4]] 3 [1, 2, 3, 4] 4
Change it and run: print a[2] and b[2].
appendadds its argument as one item (here a list inside the list).extendadds each item of its argument.
3.5Joining with +
+ builds a new list and leaves the originals unchanged:
first = [1, 2]
second = [3, 4]
both = first + second
print(both)
print(first)Output
[1, 2, 3, 4] [1, 2]
Change it and run: print second + first. The order changes.
| Way | What it adds | Changes the list itself? |
|---|---|---|
a.append(x) | one item at the end | yes |
a.insert(i, x) | one item at index i | yes |
a.extend(b) | every item of b at the end | yes |
a + b | every item of b | no, makes a new list |
3.6remove(value): remove by value
fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana")
print(fruits)Output
['apple', 'cherry', 'banana']
Change it and run: add a second fruits.remove("banana") line. Then a third one, and read the error.
Only the first matching item is removed. If the value is not in the list, Python stops with an error:
fruits = ["apple", "banana"]
fruits.remove("kiwi")Error
ValueError: list.remove(x): x not in list
The safe way is to check first:
fruits = ["apple", "banana"]
if "kiwi" in fruits:
fruits.remove("kiwi")
else:
print("kiwi is not in the list")Output
kiwi is not in the list
Change it and run: change "kiwi" to "apple" in all three places.
3.7pop(): remove by position and give the item back
fruits = ["apple", "banana", "cherry"]
last = fruits.pop()
print(last)
print(fruits)
first = fruits.pop(0)
print(first)
print(fruits)Output
cherry ['apple', 'banana'] apple ['banana']
pop()without a number removes the last item.pop(index)removes the item at that index.- In both cases the removed item is returned, so you can store and use it.
pop on an empty list is an error:
empty = []
empty.pop()Error
IndexError: pop from empty list
3.8del: delete by index or by slice
numbers = [10, 20, 30, 40, 50]
del numbers[0]
print(numbers)
del numbers[1:3]
print(numbers)Output
[20, 30, 40, 50] [20, 50]
Change it and run: delete the last item with del numbers[-1].
del is a statement, not a method. It does not give the item back.
3.9clear(): remove everything
numbers = [10, 20, 30]
numbers.clear()
print(numbers)
print(len(numbers))Output
[] 0
3.10Which one should I use?
| Tool | Removes by | Gives the item back? | Example |
|---|---|---|---|
remove(value) | value (first match) | no | fruits.remove("banana") |
pop() | last position | yes | last = fruits.pop() |
pop(index) | index | yes | first = fruits.pop(0) |
del list[index] | index or slice | no | del numbers[1:3] |
clear() | everything | no | numbers.clear() |
Press a method and watch what happens to the list.
fruits = ["apple", "banana", "cherry"]
The small numbers are the indexes.
Try it yourself
append, and print it.Show a hint
numbers = []. Loop over range(1, 11) and append each number.Show the solution
numbers = []
for number in range(1, 11):
numbers.append(number)
print(numbers)Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
4Searching, ordering, copying and operators
4.1Is it in the list? in and not in
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)
print("kiwi" in fruits)
print("kiwi" not in fruits)Output
True False True
4.2Where is it? index(value)
fruits = ["apple", "banana", "cherry", "banana"]
print(fruits.index("banana"))
print(fruits.index("cherry"))Output
1 2
Change it and run: ask for the index of "apple".
index gives the position of the first match. A missing value is an error, so check with in first:
fruits = ["apple", "banana"]
print(fruits.index("kiwi"))Error
ValueError: list.index(x): x not in list
4.3How many times? count(value)
votes = ["yes", "no", "yes", "yes", "no"]
print(votes.count("yes"))
print(votes.count("maybe"))Output
3 0
Change it and run: count "no".
4.4Built-in functions for lists: len, sum, min, max
grades = [85, 92, 78, 60, 95]
print(len(grades))
print(sum(grades))
print(min(grades))
print(max(grades))
print(sum(grades) / len(grades))Output
5 410 60 95 82.0
Change it and run: add the grade 0 to the list. Which results change?
sum(grades) / len(grades) is the average. min and max also work with text (alphabetical order):
names = ["Murad", "Aylin", "Leyla"]
print(min(names))
print(max(names))Output
Aylin Murad
4.5sort(): sort the list itself
numbers = [40, 10, 30, 20]
numbers.sort()
print(numbers)
numbers.sort(reverse=True)
print(numbers)Output
[10, 20, 30, 40] [40, 30, 20, 10]
names = ["Murad", "Aylin", "Leyla"]
names.sort()
print(names)Output
['Aylin', 'Leyla', 'Murad']
4.6sorted(): make a new sorted list
numbers = [40, 10, 30, 20]
ordered = sorted(numbers)
print(ordered)
print(numbers)Output
[10, 20, 30, 40] [40, 10, 30, 20]
Change it and run: use sorted(numbers, reverse=True).
The original list stays as it was.
| list.sort() | sorted(list) | |
|---|---|---|
| Kind | a method | a built-in function |
| Changes the original? | yes | no |
| Gives back | None | a new sorted list |
| Use it when | you no longer need the old order | you want to keep the original |
4.7A very common mistake
sort() changes the list and returns None. So this loses your list:
numbers = [40, 10, 30, 20]
numbers = numbers.sort()
print(numbers)Output
None
Change it and run: fix it in both ways.
Write numbers.sort() alone on its line, or numbers = sorted(numbers).
4.8Sorting by a rule: key
key is a function that decides what to compare. Here words are sorted by their length:
words = ["banana", "kiwi", "apple", "fig"]
words.sort(key=len)
print(words)Output
['fig', 'kiwi', 'apple', 'banana']
Change it and run: sort the same words without key. The order becomes alphabetical.
The rule can also be a lambda (from the last lesson). Here the words are sorted by their last letter, and max finds the longest word:
words = ["banana", "kiwi", "apple", "fig"]
print(sorted(words, key=lambda word: word[-1]))
print(max(words, key=len))Output
['banana', 'apple', 'fig', 'kiwi'] banana
Change it and run: sort by the second letter: word[1].
4.9reverse() and [::-1]
numbers = [1, 2, 3, 4]
numbers.reverse()
print(numbers)
letters = ["a", "b", "c"]
print(letters[::-1])
print(letters)Output
[4, 3, 2, 1] ['c', 'b', 'a'] ['a', 'b', 'c']
reverse() changes the list itself and does not sort it: it only turns the order around. [::-1] makes a new reversed list.
4.10Text and numbers cannot be sorted together
mixed = [3, "apple", 1]
mixed.sort()Error
TypeError: '<' not supported between instances of 'str' and 'int'
4.11Copying a list (an important trap)
a = [1, 2, 3]
b = a
b.append(4)
print(a)
print(b)Output
[1, 2, 3, 4] [1, 2, 3, 4]
Change it and run: append to a instead of b. Both still change.
We changed b, but a changed too. Why? b = a does not copy the list. It gives the same list a second name. There is only one list in memory.
To get a real, separate copy, use .copy():
a = [1, 2, 3]
b = a.copy()
b.append(4)
print(a)
print(b)Output
[1, 2, 3] [1, 2, 3, 4]
b = a
One list, two names
b = a.copy()
Two separate lists
b.append(4). On the left the new item is visible through both names, because there is only one list.Three ways make a copy, and all give the same result:
a = [1, 2, 3]
copy1 = a.copy()
copy2 = a[:]
copy3 = list(a)
print(copy1, copy2, copy3)Output
[1, 2, 3] [1, 2, 3] [1, 2, 3]
== checks whether two lists have the same items. is checks whether they are the same list in memory:
a = [1, 2, 3]
b = a
c = a.copy()
print(a == c)
print(a is b)
print(a is c)Output
True True False
4.12All list methods in one table
| Method | What it does | Changes the list? | Gives back |
|---|---|---|---|
append(x) | adds x at the end | yes | None |
insert(i, x) | adds x at index i | yes | None |
extend(other) | adds every item of other | yes | None |
remove(x) | removes the first x | yes | None |
pop() | removes the last item | yes | the removed item |
pop(i) | removes the item at index i | yes | the removed item |
clear() | removes all items | yes | None |
index(x) | finds the position of the first x | no | the index |
count(x) | counts how many times x appears | no | a number |
sort() | sorts the list | yes | None |
reverse() | turns the order around | yes | None |
copy() | makes a separate copy | no | a new list |
Built-in functions that take a list: len(a), sum(a), min(a), max(a), sorted(a), list(a).
Remember: the methods that change the list (append, sort, reverse, ...) return None. Do not write a = a.append(5).
4.13Operators with lists
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | join two lists | [1, 2] + [3] | [1, 2, 3] |
* | repeat a list | [0] * 4 | [0, 0, 0, 0] |
in | is the value inside? | 2 in [1, 2, 3] | True |
not in | is the value missing? | 5 not in [1, 2, 3] | True |
== | same items in the same order? | [1, 2] == [1, 2] | True |
!= | different? | [1, 2] != [2, 1] | True |
<, > | compare item by item | [1, 2] < [1, 3] | True |
print([1, 2] + [3])
print([0] * 4)
print(["ha"] * 3)
print([1, 2] == [1, 2])
print([1, 2] == [2, 1])
print([1, 2] < [1, 3])Output
[1, 2, 3] [0, 0, 0, 0] ['ha', 'ha', 'ha'] True False True
Change it and run: print [1, 2] * 2 + [3].
Order matters: [1, 2] and [2, 1] are different lists.
+= adds the items of another list (it works like extend):
numbers = [1, 2]
numbers += [3, 4]
print(numbers)Output
[1, 2, 3, 4]
A list and a single number cannot be added:
numbers = [1, 2]
numbers = numbers + 3Error
TypeError: can only concatenate list (not "int") to list
Write numbers + [3] or numbers.append(3).
Try it yourself
Show a hint
sorted(numbers, reverse=True) makes a new list. numbers.sort() would change the original.Show the solution
numbers = list(map(int, input().split()))
print(sorted(numbers, reverse=True))
print(numbers)Output
[40, 30, 20, 10] [40, 10, 30, 20]
5Going through a list with loops and if/else
This is where lists become powerful: one loop can process 5 items or 5 million.
5.1for item in list (the simplest way)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)Output
apple banana cherry
Change it and run: add a fourth fruit to the list. The loop needs no change.
The loop variable takes each item in turn. Use this when you only need the values.
5.2for i in range(len(list)) (when you need the index)
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(i, fruits[i])Output
0 apple 1 banana 2 cherry
5.3enumerate (index and item together)
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
print(i, fruit)Output
0 apple 1 banana 2 cherry
Start counting at 1 with enumerate(fruits, 1):
fruits = ["apple", "banana", "cherry"]
for number, fruit in enumerate(fruits, 1):
print(number, fruit)Output
1 apple 2 banana 3 cherry
Change it and run: start the numbering at 10.
5.4while with a list
fruits = ["apple", "banana", "cherry"]
i = 0
while i < len(fruits):
print(fruits[i])
i = i + 1Output
apple banana cherry
| Way | You get | Use it when |
|---|---|---|
for item in items: | each item | you only read the values (most common) |
for i in range(len(items)): | each index | you need positions, or you change items |
for i, item in enumerate(items): | index and item | you need both |
while i < len(items): | each index | you may stop early or move in special steps |
5.5Loop + if: the sum of the odd numbers
numbers = [3, 8, 5, 12, 7, 10]
total = 0
for number in numbers:
if number % 2 == 1:
total = total + number
print("Sum of odd numbers:", total)Output
Sum of odd numbers: 15
Change it and run: change the condition to number % 2 == 0 to add the even numbers.
Trace table:
| number | odd? | total |
|---|---|---|
| 3 | yes | 3 |
| 8 | no | 3 |
| 5 | yes | 8 |
| 12 | no | 8 |
| 7 | yes | 15 |
| 10 | no | 15 |
5.6Loop + if: counting
grades = [85, 42, 78, 60, 95, 30]
passed = 0
for grade in grades:
if grade >= 50:
passed = passed + 1
print("Passed:", passed)
print("Failed:", len(grades) - passed)Output
Passed: 4 Failed: 2
Change it and run: change the pass mark from 50 to 80.
5.7Loop + if/else: a label for every item
numbers = [4, 7, 10, 13]
for number in numbers:
if number % 2 == 0:
print(number, "is even")
else:
print(number, "is odd")Output
4 is even 7 is odd 10 is even 13 is odd
5.8Finding the largest item by hand
numbers = [12, 45, 7, 38]
largest = numbers[0]
for number in numbers:
if number > largest:
largest = number
print("Largest:", largest)Output
Largest: 45
Change it and run: change > to <. What does the loop find now?
We start with the first item, and replace largest each time we meet a bigger one. (The built-in max(numbers) does the same job, but you should understand how it works.)
5.9Building a new list from an old one
Transforming every item:
prices = [100, 250, 80]
with_tax = []
for price in prices:
with_tax.append(price * 1.2)
print(with_tax)Output
[120.0, 300.0, 96.0]
Change it and run: change the tax from 1.2 to 1.18.
Keeping only some items:
numbers = [3, 8, 5, 12, 7, 10]
evens = []
for number in numbers:
if number % 2 == 0:
evens.append(number)
print(evens)Output
[8, 12, 10]
Change it and run: keep the numbers greater than 6 instead.
Remember these two patterns. In Part 8, map does the first one and filter does the second one in a single line.
5.10Changing the items of a list in place
To change the items you need the index:
numbers = [1, 2, 3, 4]
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
print(numbers)Output
[2, 4, 6, 8]
This does not work with for number in numbers, because the loop variable is only a copy of the value:
numbers = [1, 2, 3, 4]
for number in numbers:
number = number * 2
print(numbers)Output
[1, 2, 3, 4]
5.11Searching with break
numbers = [4, 9, 15, 22, 31]
for number in numbers:
if number > 10:
print("First number above 10:", number)
breakOutput
First number above 10: 15
Change it and run: remove the break line. How many lines are printed?
5.12A while loop that empties a list
An empty list counts as False, so while tasks: means "while the list is not empty":
tasks = ["wash", "cook", "study"]
while tasks:
current = tasks.pop(0)
print("Doing:", current)
print("All done. Tasks left:", tasks)Output
Doing: wash Doing: cook Doing: study All done. Tasks left: []
Change it and run: change pop(0) to pop(). In which order are the tasks done now?
5.13Going through two lists together: zip
names = ["Aylin", "Murad", "Leyla"]
grades = [85, 92, 78]
for name, grade in zip(names, grades):
print(name, grade)Output
Aylin 85 Murad 92 Leyla 78
Change it and run: remove one grade. zip stops at the shorter list.
5.14Warning: do not remove items from a list while looping over it
numbers = [2, 4, 6, 7, 8]
for number in numbers:
if number % 2 == 0:
numbers.remove(number)
print(numbers)Output
[4, 7]
Change it and run: start with [2, 2, 4, 4] and predict the result.
We wanted to remove all even numbers, but 4 is still there. When an item is removed, the others move left and the loop skips one. The safe way is to build a new list:
numbers = [2, 4, 6, 7, 8]
odds = []
for number in numbers:
if number % 2 != 0:
odds.append(number)
print(odds)Output
[7]
Try it yourself
1 2 3 and 10 20 30 give [11, 22, 33].Show a hint
zip(a, b) gives the pairs. Start with an empty list and append(x + y) for every pair. A loop over range(len(a)) works too.Show the solution
a = list(map(int, input().split()))
b = list(map(int, input().split()))
sums = []
for x, y in zip(a, b):
sums.append(x + y)
print(sums)Output
[11, 22, 33]
6Input, text, nested lists and functions
6.1Reading a list from the user
In Part 1 we read exactly two numbers with a, b = map(int, input().split()). When we do not know how many numbers there are, we put all of them in a list:
numbers = list(map(int, input().split()))
print(numbers)
print("How many:", len(numbers))
print("Sum:", sum(numbers))Output
4 8 15 16 23 42 [4, 8, 15, 16, 23, 42] How many: 6 Sum: 108
Change it and run: type your own numbers, as many as you like.
Read it from the inside out:
| Piece | Result for the input 4 8 15 16 23 42 |
|---|---|
input() | "4 8 15 16 23 42" |
.split() | ['4', '8', '15', '16', '23', '42'] |
map(int, ...) | int applied to every piece |
list(...) | [4, 8, 15, 16, 23, 42] |
Without list(...) you get a map object, not a list. It has no len() and no indexes:
numbers = map(int, input().split())
print(len(numbers))Output
4 8 15
Error
TypeError: object of type 'map' has no len()
The same line for other types:
prices = list(map(float, input().split()))
print(prices)Output
2.5 10 7.25 [2.5, 10.0, 7.25]
words = input().split()
print(words)Output
red green blue ['red', 'green', 'blue']
6.2Values separated by commas
.split(",") cuts at commas instead of spaces:
numbers = list(map(int, input().split(",")))
print(numbers)Output
10,20,30 [10, 20, 30]
Change it and run: type 1,2,3,4.
6.3The count first, then the numbers
Many problems give the count n on the first line and the n numbers on the second line:
n = int(input())
numbers = list(map(int, input().split()))
print("n =", n)
print(numbers)Output
3 10 20 30 n = 3 [10, 20, 30]
6.4One number per line
When each number is on its own line, use a loop and append:
n = int(input())
numbers = []
for i in range(n):
numbers.append(int(input()))
print(numbers)Output
3 10 20 30 [10, 20, 30]
6.5Text and lists: split and join
split turns a text into a list. join does the opposite: it glues a list of texts into one text.
sentence = "Python is fun"
words = sentence.split()
print(words)
print(len(words))
joined = "-".join(words)
print(joined)
print(" ".join(words))Output
['Python', 'is', 'fun'] 3 Python-is-fun Python is fun
Change it and run: join the words with " + ".
The text before .join is the separator placed between the items.
join works only with text. A list of numbers must be converted first, and map(str, ...) does that:
numbers = [1, 2, 3]
print(", ".join(map(str, numbers)))Output
1, 2, 3
Printing a list without brackets: put a star before the list name. print(*numbers) is the same as print(1, 2, 3).
numbers = [1, 2, 3]
print(numbers)
print(*numbers)
print(*numbers, sep=", ")Output
[1, 2, 3] 1 2 3 1, 2, 3
Change it and run: use sep=" - ".
6.6Lists inside lists (nested lists)
An item of a list can be another list. This is how we store a table:
table = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
print(table[0])
print(table[1][2])
print(len(table))Output
[1, 2, 3] 6 3
Change it and run: print the middle number 5 with two indexes.
table[1] is the second row, and table[1][2] is the third item of that row.
A nested loop visits every item:
table = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
for row in table:
for item in row:
print(item, end=" ")
print()Output
1 2 3 4 5 6 7 8 9
students = [["Aylin", 85], ["Murad", 92], ["Leyla", 78]]
for student in students:
print(student[0], "has", student[1])Output
Aylin has 85 Murad has 92 Leyla has 78
6.7Lists and functions
A function can take a list as a parameter and can return a list.
def average(numbers):
return sum(numbers) / len(numbers)
print(average([10, 20, 30]))
print(average([85, 92, 78, 60]))Output
20.0 78.75
Change it and run: call it with your own list.
def only_positive(numbers):
result = []
for number in numbers:
if number > 0:
result.append(number)
return result
print(only_positive([3, -1, 0, 7, -5]))Output
[3, 7]
Change it and run: change > 0 to >= 0. Which number is added?
6.8A function can change the list you give it
Because lists are mutable, a change made inside the function is visible outside:
def add_bonus(grades):
for i in range(len(grades)):
grades[i] = grades[i] + 5
my_grades = [70, 80, 90]
add_bonus(my_grades)
print(my_grades)Output
[75, 85, 95]
Change it and run: pass my_grades.copy() instead. The original list stays the same.
If you do not want that, build and return a new list (like only_positive above), or pass a copy: add_bonus(my_grades.copy()).
Try it yourself
40 10 30 gives 10, 30, 40.Show a hint
sorted(numbers). Print without brackets with a star and a separator: print(*some_list, sep=", ").Show the solution
numbers = list(map(int, input().split()))
print(*sorted(numbers), sep=", ")Output
10, 30, 40
7Tuples
7.1Lists so far (a short review before tuples)
| Property | List |
|---|---|
| Written with | square brackets [1, 2, 3] |
| Ordered | yes, every item has an index |
| Mutable (changeable) | yes: change, add, remove items |
| Duplicates | allowed |
| Methods | many: append, insert, extend, remove, pop, sort, ... |
| Typical use | a collection that grows, shrinks, or gets edited |
Now we meet the tuple. A tuple is almost the same thing, but it cannot be changed.
7.2What is a tuple?
A tuple is an ordered collection of values, like a list, but immutable: after it is created, you cannot change, add, or remove items.
Real-life picture: a list is a shopping list written in pencil. A tuple is a date of birth or the coordinates of a city: the values belong together and should not change.
7.3Creating tuples
A tuple is written in round brackets (parentheses):
point = (3, 5)
colors = ("red", "green", "blue")
empty = ()
mixed = (1, "two", 3.0)
print(point)
print(colors)
print(empty)
print(type(point))
print(len(colors))Output
(3, 5)
('red', 'green', 'blue')
()
<class 'tuple'>
3The parentheses are optional. The commas make the tuple:
point = 3, 5
print(point)
print(type(point))Output
(3, 5) <class 'tuple'>
7.4A tuple with one item needs a comma
not_a_tuple = (5)
a_tuple = (5,)
print(type(not_a_tuple))
print(type(a_tuple))Output
<class 'int'> <class 'tuple'>
Change it and run: remove the comma from (5,).
(5) is only the number 5 in brackets. (5,) is a tuple with one item.
7.5Making a tuple from something else: tuple()
print(tuple([1, 2, 3]))
print(tuple("abc"))
print(tuple(range(4)))Output
(1, 2, 3)
('a', 'b', 'c')
(0, 1, 2, 3)7.6Reading a tuple works exactly like a list
Indexes, negative indexes, slices and len are the same:
colors = ("red", "green", "blue", "black")
print(colors[0])
print(colors[-1])
print(colors[1:3])
print(len(colors))Output
red
black
('green', 'blue')
4Change it and run: print colors[::-1].
A slice of a tuple is a tuple.
7.7A tuple cannot be changed
point = (3, 5)
point[0] = 10Error
TypeError: 'tuple' object does not support item assignment
There is no append, remove, insert, pop or sort for tuples:
point = (3, 5)
point.append(7)Error
AttributeError: 'tuple' object has no attribute 'append'
7.8The two tuple methods: count and index
Only the methods that do not change anything exist:
numbers = (4, 7, 4, 9, 4)
print(numbers.count(4))
print(numbers.index(7))Output
3 1
7.9Operators and built-in functions work
a = (1, 2)
b = (3, 4)
print(a + b)
print(a * 3)
print(2 in a)
print(a == (1, 2))
print(a < b)
grades = (85, 92, 78)
print(sum(grades), min(grades), max(grades))
print(sorted(grades))Output
(1, 2, 3, 4) (1, 2, 1, 2, 1, 2) True True True 255 78 92 [78, 85, 92]
a + b builds a new tuple. Notice that sorted() gives back a list, even for a tuple.
7.10Loops and if/else work exactly as with lists
grades = (85, 42, 78, 60)
for grade in grades:
if grade >= 50:
print(grade, "passed")
else:
print(grade, "failed")Output
85 passed 42 failed 78 passed 60 passed
numbers = (3, 8, 5, 12, 7)
total = 0
i = 0
while i < len(numbers):
if numbers[i] % 2 == 1:
total = total + numbers[i]
i = i + 1
print("Sum of odd numbers:", total)Output
Sum of odd numbers: 15
7.11Packing and unpacking
Putting values into a tuple is called packing. Taking them out into variables is unpacking:
person = ("Aylin", 20, "Baku") # packing
name, age, city = person # unpacking
print(name)
print(age)
print(city)Output
Aylin 20 Baku
Change it and run: add a fourth value and a fourth variable.
The number of variables must match the number of items:
person = ("Aylin", 20, "Baku")
name, age = personError
ValueError: too many values to unpack (expected 2, got 3)
You already used unpacking: a, b = map(int, input().split()) in Part 1 and for i, fruit in enumerate(fruits) in Part 5. enumerate and zip give tuples:
fruits = ["apple", "banana"]
print(list(enumerate(fruits)))
print(list(zip(["a", "b"], [1, 2])))Output
[(0, 'apple'), (1, 'banana')]
[('a', 1), ('b', 2)]7.12Swapping two variables
a = 5
b = 10
a, b = b, a
print(a, b)Output
10 5
The right side b, a is packed into a tuple, then unpacked into a and b.
7.13A function can return several values
In the last lesson we said a function returns one value. With a tuple, that one value can hold several:
def min_and_max(numbers):
return min(numbers), max(numbers)
result = min_and_max([4, 9, 1, 7])
print(result)
smallest, largest = min_and_max([4, 9, 1, 7])
print(smallest, largest)Output
(1, 9) 1 9
Change it and run: call it with your own numbers.
The built-in divmod works this way too:
quotient, remainder = divmod(17, 5)
print(quotient, remainder)Output
3 2
Change it and run: try divmod(200, 60): hours and minutes.
7.14How do I "change" a tuple?
You cannot change it, but you can build a new one. Either join tuples, or convert to a list, change the list, and convert back:
point = (3, 5)
point = point + (7,)
print(point)
colors = ("red", "green", "blue")
temp = list(colors)
temp[1] = "yellow"
colors = tuple(temp)
print(colors)Output
(3, 5, 7)
('red', 'yellow', 'blue')7.15Tuples inside a list
A list of tuples is a very common way to store records:
students = [("Aylin", 85), ("Murad", 92), ("Leyla", 78)]
for name, grade in students:
print(name, grade)Output
Aylin 85 Murad 92 Leyla 78
Change it and run: add a fourth student to the list.
The list can grow (new students), but each record stays fixed.
7.16List vs tuple (the differences)
| List | Tuple | |
|---|---|---|
| Brackets | [1, 2, 3] | (1, 2, 3) |
| Mutable (can change) | yes | no |
| Add / remove items | append, insert, extend, remove, pop, del, clear | not possible |
| Sort in place | sort(), reverse() | not possible (sorted() gives a list) |
| Methods | 11 common ones | only count and index |
| Indexes and slices | yes | yes |
len, sum, min, max, in, +, * | yes | yes |
| Loops | yes | yes |
| One item | [5] | (5,) (comma needed) |
| Speed and memory | a little slower and bigger | a little faster and smaller |
| Typical use | items of the same kind, the amount changes | a fixed group of values that belong together |
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
my_list[0] = 100
print(my_list)
print(my_list == [100, 2, 3])
print(my_tuple == (1, 2, 3))
print([1, 2, 3] == (1, 2, 3))Output
[100, 2, 3] True True False
A list and a tuple are never equal, even with the same items.
How to choose:
- "Grades of a class", "items in a cart", "numbers typed by the user" will grow or change: use a list.
- "A point (x, y)", "a date (day, month, year)", "a color (red, green, blue)", "the two results of a function" stay fixed: use a tuple.
- If you are not sure, use a list.
Converting between them is easy: list(my_tuple) and tuple(my_list).
Try it yourself
(4, 9, 2, 7) and print its largest item, its smallest item and its sum, each on its own line.Show a hint
max, min and sum work with tuples exactly as with lists.Show the solution
numbers = (4, 9, 2, 7)
print(max(numbers))
print(min(numbers))
print(sum(numbers))Output
9 2 22
Try it yourself
first_and_last(items) that returns the first and the last item as a tuple.Show a hint
return items[0], items[-1] returns one tuple with two items.Show the solution
def first_and_last(items):
return items[0], items[-1]
print(first_and_last([10, 20, 30, 40]))
first, last = first_and_last(["a", "b", "c"])
print(first, last)Output
(10, 40) a c
8map and filter
8.1map in detail
In Part 1 we used map(int, ...) to read numbers. Now we look at map as a general tool.
map(function, sequence)
map applies the function to every item and gives back the results. The number of results is always the same as the number of items.
8.2map with built-in functions
words = ["10", "20", "30"]
numbers = list(map(int, words))
print(numbers)
print(list(map(str, [1, 2, 3])))
print(list(map(len, ["apple", "kiwi", "fig"])))
print(list(map(abs, [-3, 5, -8])))Output
[10, 20, 30] ['1', '2', '3'] [5, 4, 3] [3, 5, 8]
Change it and run: apply float to the list of words.
8.3map gives a map object, not a list
result = map(abs, [-3, 5, -8])
print(result)
print(list(result))Output
<map object at 0x7f3a2c1b4d90> [3, 5, 8]
The numbers after at in the first line will be different on your computer. A map object is a "recipe" that produces the values one by one when something asks for them: list(), tuple(), a for loop, sum() or unpacking. Wrap it in list() when you need a real list.
print(tuple(map(abs, [-3, 5, -8])))
print(sum(map(abs, [-3, 5, -8])))
for value in map(abs, [-3, 5, -8]):
print(value)Output
(3, 5, 8) 16 3 5 8
A map object can be used only once. After that it is empty:
result = map(abs, [-3, 5, -8])
print(list(result))
print(list(result))Output
[3, 5, 8] []
8.4map with your own function
def add_tax(price):
return price * 1.2
prices = [100, 250, 80]
print(list(map(add_tax, prices)))Output
[120.0, 300.0, 96.0]
Change it and run: change the tax to 18% inside add_tax.
This is the same as the loop from Part 5:
def add_tax(price):
return price * 1.2
prices = [100, 250, 80]
with_tax = []
for price in prices:
with_tax.append(add_tax(price))
print(with_tax)Output
[120.0, 300.0, 96.0]
8.5Small one-line functions: lambda
You met lambda functions in the last lesson (Topic 3, Part 6). A short reminder: writing a whole def for a tiny function is long. A lambda is a small function without a name, written in one line:
lambda parameter: result
double = lambda n: n * 2
print(double(5))Output
10
lambda n: n * 2 means: "take n, give back n * 2". It is the same as:
def double(n):
return n * 2
print(double(5))Output
10
Lambdas are useful inside map:
numbers = [1, 2, 3, 4]
print(list(map(lambda n: n * 2, numbers)))
print(list(map(lambda n: n ** 2, numbers)))
names = ["aylin", "murad"]
print(list(map(lambda name: name.upper(), names)))Output
[2, 4, 6, 8] [1, 4, 9, 16] ['AYLIN', 'MURAD']
Change it and run: add a line that maps lambda n: n + 100 over the numbers.
8.6map with two lists
With a function of two parameters, map takes one item from each list:
a = [1, 2, 3]
b = [10, 20, 30]
print(list(map(lambda x, y: x + y, a, b)))Output
[11, 22, 33]
Change it and run: multiply the pairs instead of adding them.
8.7map works with tuples too
point = (1.6, 2.4, 3.5)
print(tuple(map(round, point)))Output
(2, 2, 4)
8.8filter
filter(function, sequence)
filter keeps only the items for which the function returns True. The function must answer a yes/no question about one item.
def is_even(n):
return n % 2 == 0
numbers = [3, 8, 5, 12, 7, 10]
print(list(filter(is_even, numbers)))Output
[8, 12, 10]
Change it and run: write is_odd and filter with it.
filter asked is_even about every number, and kept the ones where the answer was True. The items themselves are not changed.
With a lambda:
numbers = [3, 8, 5, 12, 7, 10]
print(list(filter(lambda n: n % 2 == 1, numbers)))
print(list(filter(lambda n: n > 6, numbers)))Output
[3, 5, 7] [8, 12, 7, 10]
Change it and run: keep the numbers that are divisible by 4.
This is the same as the loop with if from Part 5:
numbers = [3, 8, 5, 12, 7, 10]
odds = []
for number in numbers:
if number % 2 == 1:
odds.append(number)
print(odds)Output
[3, 5, 7]
Like map, filter gives an object that you wrap in list():
result = filter(lambda n: n > 6, [3, 8, 5, 12])
print(result)
print(list(result))Output
<filter object at 0x7f3a2c1b4d90> [8, 12]
More examples:
grades = [85, 42, 78, 60, 95, 30]
passed = list(filter(lambda g: g >= 50, grades))
print(passed)
print(len(passed))
words = ["apple", "kiwi", "banana", "fig"]
print(list(filter(lambda w: len(w) > 4, words)))
temperatures = (-3, 5, -8, 12, 0)
print(tuple(filter(lambda t: t < 0, temperatures)))Output
[85, 78, 60, 95] 4 ['apple', 'banana'] (-3, -8)
Change it and run: change the pass mark to 80. How many pass?
8.9filter(None, ...) removes "empty" values
With None instead of a function, filter keeps the truthy values and drops 0, "", None and False:
values = [0, 5, "", "hi", None, 7]
print(list(filter(None, values)))Output
[5, 'hi', 7]
8.10map vs filter (the differences)
| map | filter | |
|---|---|---|
| Job | changes every item | chooses some items |
| The function returns | the new value | True or False |
| Number of results | always the same as the input | the same or fewer |
| Are the items changed? | yes | no, they are kept as they are |
| The same job with a loop | result.append(function(item)) | if function(item): result.append(item) |
| Question it answers | "What does each item become?" | "Which items do I keep?" |
The same list and the same kind of function, two different results:
numbers = [1, 2, 3, 4, 5, 6]
print(list(map(lambda n: n * 10, numbers)))
print(list(filter(lambda n: n % 2 == 0, numbers)))Output
[10, 20, 30, 40, 50, 60] [2, 4, 6]
A classic mistake is giving map a yes/no function. You get True and False values, not the numbers:
numbers = [1, 2, 3, 4, 5, 6]
print(list(map(lambda n: n % 2 == 0, numbers)))
print(list(filter(lambda n: n % 2 == 0, numbers)))Output
[False, True, False, True, False, True] [2, 4, 6]
The same list and the same function, given to map and to filter.
numbers = [1, 2, 3, 4, 5, 6] print(list(map(lambda n: n * 2, numbers)))
| item | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| function says | 2 | 4 | 6 | 8 | 10 | 12 |
| result | 2 | 4 | 6 | 8 | 10 | 12 |
Output: [2, 4, 6, 8, 10, 12]
map puts the function's answers into the result: every item is changed, and the number of items stays the same.
8.11Which one for which problem?
| The problem says | Use | Example |
|---|---|---|
| "convert every ...", "read the numbers" | map | list(map(int, input().split())) |
| "the square / double / length of every item" | map | map(lambda n: n ** 2, numbers) |
| "make every name uppercase" | map | map(lambda s: s.upper(), names) |
| "only the even numbers", "only the positive ones" | filter | filter(lambda n: n > 0, numbers) |
| "remove the items that ...", "keep the items that ..." | filter | filter(lambda g: g >= 50, grades) |
| "how many items are ..." | filter + len | len(list(filter(..., numbers))) |
| "the sum of the squares of the odd numbers" | filter, then map | see below |
8.12Using both together
First choose, then change. "The squares of the odd numbers":
numbers = [1, 2, 3, 4, 5, 6]
odds = filter(lambda n: n % 2 == 1, numbers)
squares = map(lambda n: n ** 2, odds)
print(list(squares))Output
[1, 9, 25]
Change it and run: choose the even numbers instead and make their cubes.
In one line, with the sum:
numbers = [1, 2, 3, 4, 5, 6]
print(sum(map(lambda n: n ** 2, filter(lambda n: n % 2 == 1, numbers))))Output
35
8.13map/filter or a loop?
Both are correct. A loop is longer but can do several things at once and is easier to debug. map and filter are short and clear for one simple job on every item. If the one-line version becomes hard to read, write the loop.
Try it yourself
filter. Print the list once.Show a hint
append when number > 10. With filter: list(filter(lambda n: n > 10, numbers)).Show the solution
numbers = list(map(int, input().split()))
# with a loop
big = []
for number in numbers:
if number > 10:
big.append(number)
# with filter (the same result)
big = list(filter(lambda n: n > 10, numbers))
print(big)Output
[15, 23, 42]
Try it yourself
students = [("Aylin", 85), ("Murad", 92), ("Leyla", 78), ("Kamran", 45)], print the names of the students who passed (50 or more), the average grade, and the name of the student with the lowest grade. Print them on three lines: the list of names after Passed:, the number after Average:, and the name after Lowest:.Show a hint
student[0] is the name, student[1] the grade. filter chooses who passed, map takes the names or the grades, and min(students, key=lambda student: student[1]) finds the lowest.Show the solution
students = [("Aylin", 85), ("Murad", 92), ("Leyla", 78), ("Kamran", 45)]
passed = list(filter(lambda student: student[1] >= 50, students))
names = list(map(lambda student: student[0], passed))
print("Passed:", names)
grades = list(map(lambda student: student[1], students))
print("Average:", sum(grades) / len(grades))
lowest = min(students, key=lambda student: student[1])
print("Lowest:", lowest[0])Output
Passed: ['Aylin', 'Murad', 'Leyla'] Average: 75.0 Lowest: Kamran
9Common mistakes
The red text is the real message Python shows. Where there is no message, the program runs but gives a wrong answer: the comment shows what it prints.
Using index len(list)
Wrong
letters = ["a", "b", "c", "d", "e"] print(letters[5])
IndexError: list index out of range
Right
letters = ["a", "b", "c", "d", "e"] print(letters[-1]) print(letters[-2]) # prints: e, d
The last index is len(list) - 1, or use [-1].
numbers = numbers.sort()
Wrong
numbers = [40, 10, 30, 20] numbers = numbers.sort() print(numbers) # prints: None
Right
numbers = [40, 10, 30, 20] numbers.sort() print(numbers) # prints: [10, 20, 30, 40]
The list becomes None. Write numbers.sort() alone, or sorted(numbers).
a = a.append(5)
Wrong
a = [1, 2] a = a.append(5) print(a) # prints: None
Right
a = [1, 2] a.append(5) print(a) # prints: [1, 2, 5]
a becomes None. Write a.append(5) alone.
b = a to copy a list
Wrong
a = [1, 2, 3] b = a b.append(4) print(a) print(b) # prints: [1, 2, 3, 4], [1, 2, 3, 4]
Right
a = [1, 2, 3] b = a.copy() b.append(4) print(a) print(b) # prints: [1, 2, 3], [1, 2, 3, 4]
Both names change together. Use b = a.copy().
append when you meant extend
Wrong
a = [1, 2] a.append([3, 4]) print(a) # prints: [1, 2, [3, 4]]
Right
a = [1, 2] a.extend([3, 4]) print(a) # prints: [1, 2, 3, 4]
append puts a list inside the list. extend adds each item.
remove a value that is not there
Wrong
fruits = ["apple", "banana"]
fruits.remove("kiwi")ValueError: list.remove(x): x not in list
Right
fruits = ["apple", "banana"]
if "kiwi" in fruits:
fruits.remove("kiwi")
else:
print("kiwi is not in the list")
# prints: kiwi is not in the listCheck with in first.
Removing items while looping over the same list
Wrong
numbers = [2, 4, 6, 7, 8]
for number in numbers:
if number % 2 == 0:
numbers.remove(number)
print(numbers)
# prints: [4, 7]Right
numbers = [2, 4, 6, 7, 8]
odds = []
for number in numbers:
if number % 2 != 0:
odds.append(number)
print(odds)
# prints: [7]Some items are skipped. Build a new list.
Adding with list[len(list)] = x
Wrong
grades = [85, 92, 78] grades[3] = 100
IndexError: list assignment index out of range
Right
grades = [85, 92, 78] grades.append(100) print(grades) # prints: [85, 92, 78, 100]
list[len(list)] = x does not work. Use append(x).
Changing a tuple
Wrong
point = (3, 5) point[0] = 10
TypeError: 'tuple' object does not support item assignment
Right
point = (3, 5) point = (10, point[1]) print(point) # prints: (10, 5)
Make a new tuple, or use a list.
(5) for a one-item tuple
Wrong
single = (5) print(type(single)) # prints: <class 'int'>
Right
single = (5,) print(type(single)) # prints: <class 'tuple'>
It is just the number 5. Write (5,).
Forgetting list() around map / filter
Wrong
numbers = map(int, ["4", "8", "15"]) print(len(numbers))
TypeError: object of type 'map' has no len()
Right
numbers = list(map(int, ["4", "8", "15"])) print(len(numbers)) # prints: 3
You get a map object: no len, no indexes. Write list(map(...)).
Forgetting map(int, ...) after split()
Wrong
a, b = "5 7".split() print(a + b) # prints: 57
Right
a, b = map(int, "5 7".split()) print(a + b) # prints: 12
The items are text: "5" + "7" gives "57".
Writing map(int(), ...)
Wrong
numbers = list(map(int(), ["5", "7"]))
TypeError: 'int' object is not callable
Right
numbers = list(map(int, ["5", "7"])) print(numbers) # prints: [5, 7]
int() is called too early. Give the function itself: map(int, ...).
Using map to choose items
Wrong
numbers = [1, 2, 3, 4, 5, 6] print(list(map(lambda n: n % 2 == 0, numbers))) # prints: [False, True, False, True, False, True]
Right
numbers = [1, 2, 3, 4, 5, 6] print(list(filter(lambda n: n % 2 == 0, numbers))) # prints: [2, 4, 6]
You get a list of True/False. Use filter.
Wrong number of variables when unpacking
Wrong
person = ("Aylin", 20, "Baku")
name, age = personValueError: too many values to unpack (expected 2, got 3)
Right
person = ("Aylin", 20, "Baku") # packing
name, age, city = person # unpacking
print(name)
print(age)
print(city)
# prints: Aylin, 20, BakuMatch the number of values.
Forgetting map(int, ...):
a, b = input().split()
print(a + b)Output
5 7 57
The two texts were joined, not added.
10Solved problems (easy to medium-hard)
Every example was run, and the outputs are real.
10.1Level 1: Easy
Problem 1: Sum of two numbers on one line
a, b = map(int, input().split())
print(a + b)Output
12 30 42
Why: split cuts the line, map(int, ...) converts both pieces, and unpacking stores them in a and b.
Problem 2: First, last and middle item
numbers = [10, 20, 30, 40, 50]
print("First:", numbers[0])
print("Last:", numbers[-1])
print("Middle:", numbers[len(numbers) // 2])Output
First: 10 Last: 50 Middle: 30
Why: the first index is 0, the last is -1, and len // 2 is the middle index of a list with an odd number of items.
Problem 3: Sum and average of a list read from the user
numbers = list(map(int, input().split()))
total = sum(numbers)
print("Sum:", total)
print("Average:", total / len(numbers))Output
10 20 30 40 Sum: 100 Average: 25.0
Change it and run: type your own numbers.
Problem 4: Count the even and the odd numbers
numbers = [3, 8, 5, 12, 7, 10, 1]
even = 0
odd = 0
for number in numbers:
if number % 2 == 0:
even = even + 1
else:
odd = odd + 1
print("Even:", even)
print("Odd:", odd)Output
Even: 3 Odd: 4
Why: two counters and one if/else inside the loop.
Problem 5: Sum of the odd numbers, three ways
numbers = [3, 8, 5, 12, 7, 10]
# 1. loop and if
total = 0
for number in numbers:
if number % 2 == 1:
total = total + number
print(total)
# 2. while loop
total = 0
i = 0
while i < len(numbers):
if numbers[i] % 2 == 1:
total = total + numbers[i]
i = i + 1
print(total)
# 3. filter
print(sum(filter(lambda n: n % 2 == 1, numbers)))Output
15 15 15
Why: all three do the same job. filter chooses the odd numbers and sum adds them.
Problem 6: Build a shopping list
shopping = []
shopping.append("milk")
shopping.append("bread")
shopping.insert(0, "eggs")
shopping.extend(["rice", "tea"])
shopping.remove("bread")
print(shopping)
print("Items:", len(shopping))Output
['eggs', 'milk', 'rice', 'tea'] Items: 4
Problem 7: Largest and smallest without max and min
numbers = [12, 45, 7, 38, 21]
largest = numbers[0]
smallest = numbers[0]
for number in numbers:
if number > largest:
largest = number
if number < smallest:
smallest = number
print("Largest:", largest)
print("Smallest:", smallest)Output
Largest: 45 Smallest: 7
Why: two separate if statements (not elif), because each number must be compared with both.
Problem 8: Swap the first and the last item
numbers = [1, 2, 3, 4, 5]
numbers[0], numbers[-1] = numbers[-1], numbers[0]
print(numbers)Output
[5, 2, 3, 4, 1]
Why: tuple packing and unpacking swaps two values without a helper variable.
Problem 9: Unpack a tuple
date = (15, 3, 2026)
day, month, year = date
print("Day:", day)
print("Month:", month)
print("Year:", year)Output
Day: 15 Month: 3 Year: 2026
10.2Level 2: Medium
Problem 10: Reverse a list in three ways
numbers = [1, 2, 3, 4, 5]
print(numbers[::-1])
reversed_list = []
for number in numbers:
reversed_list.insert(0, number)
print(reversed_list)
numbers.reverse()
print(numbers)Output
[5, 4, 3, 2, 1] [5, 4, 3, 2, 1] [5, 4, 3, 2, 1]
Why: the slice makes a new list, the loop puts each item in front, and reverse() changes the list itself.
Problem 11: The second largest number
numbers = [12, 45, 7, 45, 38, 21]
largest = max(numbers)
others = list(filter(lambda n: n != largest, numbers))
print("Second largest:", max(others))Output
Second largest: 38
Change it and run: change the list to [5, 5, 5, 2].
Why: remove every copy of the largest value with filter, then the largest of the rest is the answer. (Sorting and taking [-2] would give 45 again, because 45 appears twice.)
Problem 12: Remove duplicates and keep the order
numbers = [3, 5, 3, 8, 5, 3, 9]
unique = []
for number in numbers:
if number not in unique:
unique.append(number)
print(unique)Output
[3, 5, 8, 9]
Why: an item is added only if it is not in the new list yet.
Problem 13: Squares with a loop and with map
numbers = [1, 2, 3, 4, 5]
squares = []
for number in numbers:
squares.append(number ** 2)
print(squares)
print(list(map(lambda n: n ** 2, numbers)))Output
[1, 4, 9, 16, 25] [1, 4, 9, 16, 25]
Problem 14: Grades report
grades = list(map(int, input().split()))
passed = list(filter(lambda g: g >= 50, grades))
print("Grades:", grades)
print("Highest:", max(grades))
print("Lowest:", min(grades))
print("Average:", round(sum(grades) / len(grades), 2))
print("Passed:", len(passed), "of", len(grades))Output
85 42 78 60 95 30 Grades: [85, 42, 78, 60, 95, 30] Highest: 95 Lowest: 30 Average: 65.0 Passed: 4 of 6
Change it and run: type your own grades.
Problem 15: Find the position of a value (linear search)
numbers = [14, 9, 27, 3, 18]
target = 27
position = -1
for i in range(len(numbers)):
if numbers[i] == target:
position = i
break
if position == -1:
print(target, "is not in the list")
else:
print(target, "is at index", position)Output
27 is at index 2
Change it and run: set target to 100.
Why: we need the index, so we loop over range(len(numbers)), and break stops at the first match. (numbers.index(27) does the same job, but gives an error when the value is missing.)
Problem 16: Count how many times each value appears
votes = ["yes", "no", "yes", "yes", "no", "maybe"]
seen = []
for vote in votes:
if vote not in seen:
seen.append(vote)
print(vote, votes.count(vote))Output
yes 3 no 2 maybe 1
Problem 17: Celsius to Fahrenheit for a whole list
celsius = [0, 20, 37, 100]
fahrenheit = list(map(lambda c: c * 9 / 5 + 32, celsius))
print(fahrenheit)
for c, f in zip(celsius, fahrenheit):
print(c, "C =", f, "F")Output
[32.0, 68.0, 98.6, 212.0] 0 C = 32.0 F 20 C = 68.0 F 37 C = 98.6 F 100 C = 212.0 F
Problem 18: A function that returns two values
def sum_and_average(numbers):
total = sum(numbers)
return total, total / len(numbers)
total, average = sum_and_average([10, 20, 30, 40])
print("Sum:", total)
print("Average:", average)Output
Sum: 100 Average: 25.0
Why: return total, total / len(numbers) returns one tuple with two items, and we unpack it.
Problem 19: Words of a sentence
sentence = "python makes data science easier"
words = sentence.split()
print("Words:", len(words))
print("Longest:", max(words, key=len))
print("Capitalized:", " ".join(map(lambda w: w.capitalize(), words)))
print("Long words:", list(filter(lambda w: len(w) > 5, words)))Output
Words: 5 Longest: science Capitalized: Python Makes Data Science Easier Long words: ['python', 'science', 'easier']
10.3Level 3: Medium-Hard
Problem 20: Merge two lists and sort the result
a = [5, 1, 9]
b = [4, 8, 2]
merged = sorted(a + b)
print(merged)
print(a, b)Output
[1, 2, 4, 5, 8, 9] [5, 1, 9] [4, 8, 2]
Why: a + b makes a new list and sorted makes a new sorted list, so a and b are unchanged.
Problem 21: Split a list into positives, negatives and zeros
numbers = [4, -2, 0, 7, -9, 0, 3]
positives = []
negatives = []
zeros = 0
for number in numbers:
if number > 0:
positives.append(number)
elif number < 0:
negatives.append(number)
else:
zeros = zeros + 1
print("Positive:", positives)
print("Negative:", negatives)
print("Zeros:", zeros)Output
Positive: [4, 7, 3] Negative: [-2, -9] Zeros: 2
Problem 22: Rotate a list one step to the right
numbers = [1, 2, 3, 4, 5]
last = numbers.pop()
numbers.insert(0, last)
print(numbers)Output
[5, 1, 2, 3, 4]
Change it and run: copy the two middle lines once more to rotate two steps.
Why: pop() removes the last item and gives it back, and insert(0, ...) puts it in front.
Problem 23: Running total
Each item of the new list is the sum of all numbers so far.
numbers = [5, 3, 8, 2]
running = []
total = 0
for number in numbers:
total = total + number
running.append(total)
print(running)Output
[5, 8, 16, 18]
Problem 24: The best student in a list of tuples
students = [("Aylin", 85), ("Murad", 92), ("Leyla", 78)]
best_name = students[0][0]
best_grade = students[0][1]
for name, grade in students:
if grade > best_grade:
best_name = name
best_grade = grade
print("Best student:", best_name, "with", best_grade)Output
Best student: Murad with 92
Why: each item is a tuple, and for name, grade in students unpacks it in every round.
Problem 25: Sum of every row and of the whole table
table = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
row_sums = list(map(sum, table))
print("Row sums:", row_sums)
print("Total:", sum(row_sums))Output
Row sums: [6, 15, 24] Total: 45
Why: every item of table is a list, so map(sum, table) runs sum on every row.
Problem 26: Read the numbers, keep the even ones, square them, add them up
numbers = list(map(int, input().split()))
evens = list(filter(lambda n: n % 2 == 0, numbers))
squares = list(map(lambda n: n ** 2, evens))
print("Numbers:", numbers)
print("Even:", evens)
print("Squares:", squares)
print("Sum:", sum(squares))Output
1 2 3 4 5 6 Numbers: [1, 2, 3, 4, 5, 6] Even: [2, 4, 6] Squares: [4, 16, 36] Sum: 56
Change it and run: type 10 11 12.
Why: filter chooses, map changes, sum adds. Three small steps, each one easy to check.
11Practice problems (try them yourself)
Fifteen problems in three levels. The first lines in each editor read the input for you. Press Run to try one input, then Check to run your code with several inputs, including a list with one item and lists with zeros or negative numbers.
Easy
Reading input, indexes and the built-in functions.
- 1.Read three whole numbers from one line and print their product.Examples:
2 3 4gives241 1 1gives15 0 9gives0Show a hint
a, b, c = map(int, input().split())reads all three. Then multiply them.Show one possible solution
Pythona, b, c = map(int, input().split()) print(a * b * c)Output
24
- 2.Read a list of numbers from one line and print the first and the last item, on one line with a space between them.Examples:
4 8 15 16gives4 167gives7 71 2gives1 2Show a hint
The first item isnumbers[0], the last isnumbers[-1].print(a, b)puts a space between two values.Show one possible solution
Pythonnumbers = list(map(int, input().split())) print(numbers[0], numbers[-1])Output
4 16
- 3.Read a list of numbers and print how many items it has, their sum, the smallest and the largest, on one line with spaces between them.Examples:
10 20 30 40gives4 100 10 405gives1 5 5 53 -1 4 -1 5gives5 10 -1 5Show a hint
Four built-in functions do all the work:len,sum,min,max.Show one possible solution
Pythonnumbers = list(map(int, input().split())) print(len(numbers), sum(numbers), min(numbers), max(numbers))Output
4 100 10 40
- 4.Read a list of numbers and print the sum of the even numbers.Examples:
3 8 5 12 7 10gives301 3 5gives02gives2Show a hint
An accumulator that starts at 0, aforloop over the list, andif number % 2 == 0inside it.Show one possible solution
Pythonnumbers = list(map(int, input().split())) total = 0 for number in numbers: if number % 2 == 0: total = total + number print(total)Output
30
- 5.Read a list of numbers and a target number (on the second line). Print how many times the target appears in the list.Examples:
1 2 2 3 2, 2gives35 5 5, 5gives31 2 3, 9gives0Show a hint
One list method answers this:count.Show one possible solution
Pythonnumbers = list(map(int, input().split())) target = int(input()) print(numbers.count(target))Output
3
Medium
Loops, methods, a function, and the first map.
- 6.Read a list of numbers and print them in reverse order on one line, with spaces between them and without brackets.Examples:
1 2 3 4 5gives5 4 3 2 17gives710 20gives20 10Show a hint
numbers[::-1]is the reversed list. A star prints a list without brackets:print(*some_list).Show one possible solution
Pythonnumbers = list(map(int, input().split())) print(*numbers[::-1])Output
5 4 3 2 1
- 7.Read a list of numbers and print a new list where every number is doubled. Solve it with a loop, then with
map. Print the list once.Examples:1 2 3gives[2, 4, 6]0gives[0]-4 5gives[-8, 10]Show a hint
Loop: start with an empty list andappend(number * 2). Withmap:list(map(lambda n: n * 2, numbers)).Show one possible solution
Pythonnumbers = list(map(int, input().split())) # with a loop doubled = [] for number in numbers: doubled.append(number * 2) # with map (the same result) doubled = list(map(lambda n: n * 2, numbers)) print(doubled)Output
[2, 4, 6]
- 8.Read a list of words from one line and print the longest word and its length, with a space between them. If several words have the same length, print the first of them.Examples:
python makes data science easiergivesscience 7a bb ccgivesbb 2hellogiveshello 5Show a hint
max(words, key=len)gives the longest word (the first one when several are equally long).Show one possible solution
Pythonwords = input().split() longest = max(words, key=len) print(longest, len(longest))Output
science 7
- 9.Write a function
count_above(numbers, limit)that returns how many numbers are greater thanlimit.Examples:3 8 5 12 7, 6gives31 2 3, 3gives010 10 10, 9gives3Show a hint
The counter pattern inside a function: start at 0, add 1 whennumber > limit, andreturnthe counter after the loop.Show one possible solution
Pythondef count_above(numbers, limit): count = 0 for number in numbers: if number > limit: count = count + 1 return count numbers = list(map(int, input().split())) limit = int(input()) print(count_above(numbers, limit))Output
3
- 10.Read a list of numbers and print
Trueif the list is sorted from smallest to largest, otherwiseFalse.Examples:1 2 3 4givesTrue1 3 2givesFalse5givesTrueShow a hint
Compare the list with its sorted version:numbers == sorted(numbers). Or loop over the indexes and compare each item with the next one.Show one possible solution
Pythonnumbers = list(map(int, input().split())) print(numbers == sorted(numbers))Output
True
Medium-Hard
Several steps together, with filter and map.
- 11.Read a list of numbers and remove all duplicates, keeping the first appearance of each number. Print the new list.Examples:
3 5 3 8 5 3 9gives[3, 5, 8, 9]1 1 1gives[1]4gives[4]Show a hint
Build a new list: add a number only when it isnot inthe new list yet (solved problem 12).Show one possible solution
Pythonnumbers = list(map(int, input().split())) unique = [] for number in numbers: if number not in unique: unique.append(number) print(unique)Output
[3, 5, 8, 9]
- 12.Read a list of numbers and print the second smallest different number. The list always has at least two different numbers. Example:
4 1 7 1 3gives3.Examples:4 1 7 1 3gives35 5 6gives610 9gives10Show a hint
Find the smallest withmin. Keep only the numbers that are different from it (filter, or a loop withif). The smallest of the rest is the answer (solved problem 11 does this for the largest).Show one possible solution
Pythonnumbers = list(map(int, input().split())) smallest = min(numbers) others = list(filter(lambda n: n != smallest, numbers)) print(min(others))Output
3
- 13.Read a list of numbers and print the sum of the squares of the odd numbers. Use
filterandmap.Examples:1 2 3 4 5 6gives352 4 6gives07gives49Show a hint
First choose, then change, then add:filterkeeps the odd numbers,mapsquares them,sumadds them.Show one possible solution
Pythonnumbers = list(map(int, input().split())) odds = filter(lambda n: n % 2 == 1, numbers) squares = map(lambda n: n ** 2, odds) print(sum(squares))Output
35
- 14.Read a list of numbers and move all zeros to the end, keeping the order of the other numbers. Print the new list. Example:
0 3 0 5 1gives[3, 5, 1, 0, 0].Examples:0 3 0 5 1gives[3, 5, 1, 0, 0]1 2 3gives[1, 2, 3]0 0 0gives[0, 0, 0]Show a hint
Make a list of the numbers that are not zero. Count the zeros withcount(0). Then join:others + [0] * zeros.Show one possible solution
Pythonnumbers = list(map(int, input().split())) others = list(filter(lambda n: n != 0, numbers)) zeros = numbers.count(0) print(others + [0] * zeros)Output
[3, 5, 1, 0, 0]
- 15.Read a list of numbers and rotate it
ksteps to the right (kis on the second line). Print the list. Example:1 2 3 4 5withk = 2gives[4, 5, 1, 2, 3].Examples:1 2 3 4 5, 2gives[4, 5, 1, 2, 3]1 2 3, 0gives[1, 2, 3]1 2 3, 3gives[1, 2, 3]Show a hint
One step:pop()takes the last item andinsert(0, ...)puts it in front (solved problem 22). Repeat itktimes with a loop.Show one possible solution
Pythonnumbers = list(map(int, input().split())) k = int(input()) for step in range(k): last = numbers.pop() numbers.insert(0, last) print(numbers)Output
[4, 5, 1, 2, 3]
12Check yourself
Twelve quick questions. Your answers are saved in this browser, so you can leave the page and continue later. Each finished round is kept as an attempt below the questions; you can delete the attempts at any time.
0 of 12 answered.
13Quick summary
| Concept | What it does | Example |
|---|---|---|
| List | ordered, changeable collection | [1, 2, 3] |
| Tuple | ordered, unchangeable collection | (1, 2, 3) |
| Index | position of an item, from 0 | items[0], items[-1] |
| Slice | a part of the collection | items[1:4], items[::-1] |
append / insert / extend | add items to a list | items.append(5) |
remove / pop / del / clear | remove items from a list | items.pop() |
index / count / in | search | items.count(3) |
sort / sorted / reverse | order | sorted(items) |
copy | a separate copy of a list | b = a.copy() |
len / sum / min / max | calculate | sum(items) / len(items) |
for item in items | go through the items | loop + if |
enumerate | index and item together | for i, x in enumerate(items): |
| Unpacking | values into variables | a, b = (1, 2) |
split / join | text to list / list to text | "a b".split() |
| Read two numbers | one line of input | a, b = map(int, input().split()) |
| Read a list | one line of input | list(map(int, input().split())) |
map | changes every item | map(lambda n: n * 2, items) |
filter | keeps some items | filter(lambda n: n > 0, items) |
lambda | a small function in one line | lambda n: n * 2 |