Asiman Data School

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

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. 1.How map reads several values in one line: a, b = map(int, input().split())
  2. 2.What a list is, and how to create, read, change, grow, shrink, search, sort and copy one
  3. 3.Every common list method and when to use it
  4. 4.Operators, if/else, for and while applied to lists
  5. 5.How to read a whole list from the user: numbers = list(map(int, input().split()))
  6. 6.What a tuple is, how it differs from a list, and when to use each
  7. 7.map and filter: what each one does, their differences, and which problems each one solves
  8. 8.26 solved problems and practice problems

1Reading several values in one line with map

Until now we read one value per line:

Python
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

Python
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

Python
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.

Python
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

Python
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:

All three steps in one line
PieceWhat it doesResult 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 piece5 and 7
a, b = ...stores the results in two variablesa is 5, b is 7
  1. input()

    "5 7"

    one text

  2. .split()

    ['5', '7']

    a list of texts

  3. map(int, ...)

    5 7

    two numbers

  4. a, b = ...

    a = 5 b = 7

    two variables

The line a, b = map(int, input().split()) does these four steps, from the inside out.

1.5The same idea with other types and more values

Python
a, b, c = map(int, input().split())
print(a + b + c)

Output

3 10 4
17
Python
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:

Python
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:

Python
a, b = map(int, input().split())

Output

5 7 9

Error

ValueError: too many values to unpack (expected 2)

And with too few values:

Python
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

Read the width and the height of a rectangle from one line (two whole numbers) and print its area.
Show a hint
width, height = map(int, input().split()) reads both numbers. Then multiply them.
Show the solution
Python
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:

Python
grade1 = 85
grade2 = 92
grade3 = 78
grade4 = 60
grade5 = 95

Now imagine 500 students. A list stores many values in one variable, in order:

Python
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:

Python
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()

Python
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()

Python
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.

index01234
item"a""b""c""d""e"
negative-5-4-3-2-1
Counting from the front starts at 0. Counting from the back starts at -1, so letters[-1] is always the last item.
Python
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:

Python
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:

Python
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).

Python
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.

Slices: taking a part of a list
SliceMeaning
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:

Python
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:

Python
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])
The items with their indexes; the chosen items are highlighted
012345
102030405060
-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).

Python
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:

Python
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:

Python
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:

Python
grades = [85, 92, 78]
grades[3] = 100

Error

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

From the list 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
Python
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

Python
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:

Python
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

Python
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

Python
fruits = ["apple", "banana"]
fruits.extend(["cherry", "orange"])
print(fruits)

Output

['apple', 'banana', 'cherry', 'orange']

3.4append vs extend (a classic confusion)

Python
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].

  • append adds its argument as one item (here a list inside the list).
  • extend adds each item of its argument.

3.5Joining with +

+ builds a new list and leaves the originals unchanged:

Python
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.

Joining with +
WayWhat it addsChanges the list itself?
a.append(x)one item at the endyes
a.insert(i, x)one item at index iyes
a.extend(b)every item of b at the endyes
a + bevery item of bno, makes a new list

3.6remove(value): remove by value

Python
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:

Python
fruits = ["apple", "banana"]
fruits.remove("kiwi")

Error

ValueError: list.remove(x): x not in list

The safe way is to check first:

Python
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

Python
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:

Python
empty = []
empty.pop()

Error

IndexError: pop from empty list

3.8del: delete by index or by slice

Python
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

Python
numbers = [10, 20, 30]
numbers.clear()
print(numbers)
print(len(numbers))

Output

[]
0

3.10Which one should I use?

Which one should I use?
ToolRemoves byGives the item back?Example
remove(value)value (first match)nofruits.remove("banana")
pop()last positionyeslast = fruits.pop()
pop(index)indexyesfirst = fruits.pop(0)
del list[index]index or slicenodel numbers[1:3]
clear()everythingnonumbers.clear()

Press a method and watch what happens to the list.

fruits = ["apple", "banana", "cherry"]
0apple
1banana
2cherry

The small numbers are the indexes.

Try it yourself

Create an empty list, add the numbers from 1 to 10 with a loop and append, and print it.
Show a hint
Start with numbers = []. Loop over range(1, 11) and append each number.
Show the solution
Python
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

Python
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)

Python
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:

Python
fruits = ["apple", "banana"]
print(fruits.index("kiwi"))

Error

ValueError: list.index(x): x not in list

4.3How many times? count(value)

Python
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

Python
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):

Python
names = ["Murad", "Aylin", "Leyla"]
print(min(names))
print(max(names))

Output

Aylin
Murad

4.5sort(): sort the list itself

Python
numbers = [40, 10, 30, 20]
numbers.sort()
print(numbers)

numbers.sort(reverse=True)
print(numbers)

Output

[10, 20, 30, 40]
[40, 30, 20, 10]
Python
names = ["Murad", "Aylin", "Leyla"]
names.sort()
print(names)

Output

['Aylin', 'Leyla', 'Murad']

4.6sorted(): make a new sorted list

Python
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.

sorted(): make a new sorted list
list.sort()sorted(list)
Kinda methoda built-in function
Changes the original?yesno
Gives backNonea new sorted list
Use it whenyou no longer need the old orderyou want to keep the original

4.7A very common mistake

sort() changes the list and returns None. So this loses your list:

Python
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:

Python
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:

Python
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]

Python
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

Python
mixed = [3, "apple", 1]
mixed.sort()

Error

TypeError: '<' not supported between instances of 'str' and 'int'

4.11Copying a list (an important trap)

Python
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():

Python
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

ab
1234

b = a.copy()

Two separate lists

a
123
b
1234
Both pictures show the lists after 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:

Python
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:

Python
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

All list methods in one table
MethodWhat it doesChanges the list?Gives back
append(x)adds x at the endyesNone
insert(i, x)adds x at index iyesNone
extend(other)adds every item of otheryesNone
remove(x)removes the first xyesNone
pop()removes the last itemyesthe removed item
pop(i)removes the item at index iyesthe removed item
clear()removes all itemsyesNone
index(x)finds the position of the first xnothe index
count(x)counts how many times x appearsnoa number
sort()sorts the listyesNone
reverse()turns the order aroundyesNone
copy()makes a separate copynoa 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

Operators with lists
OperatorMeaningExampleResult
+join two lists[1, 2] + [3][1, 2, 3]
*repeat a list[0] * 4[0, 0, 0, 0]
inis the value inside?2 in [1, 2, 3]True
not inis 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
Python
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):

Python
numbers = [1, 2]
numbers += [3, 4]
print(numbers)

Output

[1, 2, 3, 4]

A list and a single number cannot be added:

Python
numbers = [1, 2]
numbers = numbers + 3

Error

TypeError: can only concatenate list (not "int") to list

Write numbers + [3] or numbers.append(3).

Try it yourself

Read a list of numbers and print it sorted from largest to smallest, without changing the original list. Print the original list too, on the second line.
Show a hint
sorted(numbers, reverse=True) makes a new list. numbers.sort() would change the original.
Show the solution
Python
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)

Python
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)

Python
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)

Python
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):

Python
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

Python
fruits = ["apple", "banana", "cherry"]
i = 0
while i < len(fruits):
    print(fruits[i])
    i = i + 1

Output

apple
banana
cherry
while with a list
WayYou getUse it when
for item in items:each itemyou only read the values (most common)
for i in range(len(items)):each indexyou need positions, or you change items
for i, item in enumerate(items):index and itemyou need both
while i < len(items):each indexyou may stop early or move in special steps

5.5Loop + if: the sum of the odd numbers

Python
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:

Loop + if: the sum of the odd numbers
numberodd?total
3yes3
8no3
5yes8
12no8
7yes15
10no15

5.6Loop + if: counting

Python
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

Python
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

Python
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:

Python
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:

Python
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:

Python
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:

Python
numbers = [1, 2, 3, 4]
for number in numbers:
    number = number * 2
print(numbers)

Output

[1, 2, 3, 4]

5.11Searching with break

Python
numbers = [4, 9, 15, 22, 31]
for number in numbers:
    if number > 10:
        print("First number above 10:", number)
        break

Output

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":

Python
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

Python
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

Python
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:

Python
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

Read two lists of the same length (two lines) and print a list with the sums of the items at the same positions. Example: 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
Python
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:

Python
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:

Reading a list from the user
PieceResult 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:

Python
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:

Python
prices = list(map(float, input().split()))
print(prices)

Output

2.5 10 7.25
[2.5, 10.0, 7.25]
Python
words = input().split()
print(words)

Output

red green blue
['red', 'green', 'blue']

6.2Values separated by commas

.split(",") cuts at commas instead of spaces:

Python
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:

Python
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:

Python
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.

Python
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:

Python
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).

Python
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:

Python
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:

Python
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
Python
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.

Python
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.

Python
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:

Python
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

Read numbers from one line and print them sorted from smallest to largest on one line, separated by a comma and a space, without brackets. Example: 40 10 30 gives 10, 30, 40.
Show a hint
Sort with sorted(numbers). Print without brackets with a star and a separator: print(*some_list, sep=", ").
Show the solution
Python
numbers = list(map(int, input().split()))
print(*sorted(numbers), sep=", ")

Output

10, 30, 40

7Tuples

7.1Lists so far (a short review before tuples)

Lists so far (a short review before tuples)
PropertyList
Written withsquare brackets [1, 2, 3]
Orderedyes, every item has an index
Mutable (changeable)yes: change, add, remove items
Duplicatesallowed
Methodsmany: append, insert, extend, remove, pop, sort, ...
Typical usea 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):

Python
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'>
3

The parentheses are optional. The commas make the tuple:

Python
point = 3, 5
print(point)
print(type(point))

Output

(3, 5)
<class 'tuple'>

7.4A tuple with one item needs a comma

Python
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()

Python
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:

Python
colors = ("red", "green", "blue", "black")
print(colors[0])
print(colors[-1])
print(colors[1:3])
print(len(colors))

Output

red
black
('green', 'blue')
4

Change it and run: print colors[::-1].

A slice of a tuple is a tuple.

7.7A tuple cannot be changed

Python
point = (3, 5)
point[0] = 10

Error

TypeError: 'tuple' object does not support item assignment

There is no append, remove, insert, pop or sort for tuples:

Python
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:

Python
numbers = (4, 7, 4, 9, 4)
print(numbers.count(4))
print(numbers.index(7))

Output

3
1

7.9Operators and built-in functions work

Python
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

Python
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
Python
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:

Python
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:

Python
person = ("Aylin", 20, "Baku")
name, age = person

Error

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:

Python
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

Python
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:

Python
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:

Python
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:

Python
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:

Python
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 vs tuple (the differences)
ListTuple
Brackets[1, 2, 3](1, 2, 3)
Mutable (can change)yesno
Add / remove itemsappend, insert, extend, remove, pop, del, clearnot possible
Sort in placesort(), reverse()not possible (sorted() gives a list)
Methods11 common onesonly count and index
Indexes and slicesyesyes
len, sum, min, max, in, +, *yesyes
Loopsyesyes
One item[5](5,) (comma needed)
Speed and memorya little slower and biggera little faster and smaller
Typical useitems of the same kind, the amount changesa fixed group of values that belong together
Python
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

Create the tuple (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
Python
numbers = (4, 9, 2, 7)
print(max(numbers))
print(min(numbers))
print(sum(numbers))

Output

9
2
22

Try it yourself

Write a function 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
Python
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

Python
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

Python
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.

Python
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:

Python
result = map(abs, [-3, 5, -8])
print(list(result))
print(list(result))

Output

[3, 5, 8]
[]

8.4map with your own function

Python
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:

Python
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
Python
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:

Python
def double(n):
    return n * 2

print(double(5))

Output

10

Lambdas are useful inside map:

Python
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:

Python
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

Python
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.

Python
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:

Python
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:

Python
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():

Python
result = filter(lambda n: n > 6, [3, 8, 5, 12])
print(result)
print(list(result))

Output

<filter object at 0x7f3a2c1b4d90>
[8, 12]

More examples:

Python
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:

Python
values = [0, 5, "", "hi", None, 7]
print(list(filter(None, values)))

Output

[5, 'hi', 7]

8.10map vs filter (the differences)

map vs filter (the differences)
mapfilter
Jobchanges every itemchooses some items
The function returnsthe new valueTrue or False
Number of resultsalways the same as the inputthe same or fewer
Are the items changed?yesno, they are kept as they are
The same job with a loopresult.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:

Python
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:

Python
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)))
Each number and what map makes of it
item123456
function says24681012
result24681012

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?

Which one for which problem?
The problem saysUseExample
"convert every ...", "read the numbers"maplist(map(int, input().split()))
"the square / double / length of every item"mapmap(lambda n: n ** 2, numbers)
"make every name uppercase"mapmap(lambda s: s.upper(), names)
"only the even numbers", "only the positive ones"filterfilter(lambda n: n > 0, numbers)
"remove the items that ...", "keep the items that ..."filterfilter(lambda g: g >= 50, grades)
"how many items are ..."filter + lenlen(list(filter(..., numbers)))
"the sum of the squares of the odd numbers"filter, then mapsee below

8.12Using both together

First choose, then change. "The squares of the odd numbers":

Python
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:

Python
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

Read a list of numbers and print a list with only the numbers greater than 10. Solve it with a loop, then with filter. Print the list once.
Show a hint
Loop: an empty list, and append when number > 10. With filter: list(filter(lambda n: n > 10, numbers)).
Show the solution
Python
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

Given 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
Each student is a tuple: 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
Python
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 list

Check 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 = person
ValueError: 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, Baku

Match the number of values.

Forgetting map(int, ...):

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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)

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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.

Python
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

Python
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

Python
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

Python
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. 1.Read three whole numbers from one line and print their product.Examples: 2 3 4 gives 241 1 1 gives 15 0 9 gives 0
    Show a hint
    a, b, c = map(int, input().split()) reads all three. Then multiply them.
    Show one possible solution
    Python
    a, b, c = map(int, input().split())
    print(a * b * c)

    Output

    24
  2. 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 16 gives 4 167 gives 7 71 2 gives 1 2
    Show a hint
    The first item is numbers[0], the last is numbers[-1]. print(a, b) puts a space between two values.
    Show one possible solution
    Python
    numbers = list(map(int, input().split()))
    print(numbers[0], numbers[-1])

    Output

    4 16
  3. 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 40 gives 4 100 10 405 gives 1 5 5 53 -1 4 -1 5 gives 5 10 -1 5
    Show a hint
    Four built-in functions do all the work: len, sum, min, max.
    Show one possible solution
    Python
    numbers = list(map(int, input().split()))
    print(len(numbers), sum(numbers), min(numbers), max(numbers))

    Output

    4 100 10 40
  4. 4.Read a list of numbers and print the sum of the even numbers.Examples: 3 8 5 12 7 10 gives 301 3 5 gives 02 gives 2
    Show a hint
    An accumulator that starts at 0, a for loop over the list, and if number % 2 == 0 inside it.
    Show one possible solution
    Python
    numbers = list(map(int, input().split()))
    total = 0
    for number in numbers:
        if number % 2 == 0:
            total = total + number
    print(total)

    Output

    30
  5. 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, 2 gives 35 5 5, 5 gives 31 2 3, 9 gives 0
    Show a hint
    One list method answers this: count.
    Show one possible solution
    Python
    numbers = list(map(int, input().split()))
    target = int(input())
    print(numbers.count(target))

    Output

    3

Medium

Loops, methods, a function, and the first map.

  1. 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 5 gives 5 4 3 2 17 gives 710 20 gives 20 10
    Show a hint
    numbers[::-1] is the reversed list. A star prints a list without brackets: print(*some_list).
    Show one possible solution
    Python
    numbers = list(map(int, input().split()))
    print(*numbers[::-1])

    Output

    5 4 3 2 1
  2. 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 3 gives [2, 4, 6]0 gives [0]-4 5 gives [-8, 10]
    Show a hint
    Loop: start with an empty list and append(number * 2). With map: list(map(lambda n: n * 2, numbers)).
    Show one possible solution
    Python
    numbers = 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]
  3. 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 easier gives science 7a bb cc gives bb 2hello gives hello 5
    Show a hint
    max(words, key=len) gives the longest word (the first one when several are equally long).
    Show one possible solution
    Python
    words = input().split()
    longest = max(words, key=len)
    print(longest, len(longest))

    Output

    science 7
  4. 9.Write a function count_above(numbers, limit) that returns how many numbers are greater than limit.Examples: 3 8 5 12 7, 6 gives 31 2 3, 3 gives 010 10 10, 9 gives 3
    Show a hint
    The counter pattern inside a function: start at 0, add 1 when number > limit, and return the counter after the loop.
    Show one possible solution
    Python
    def 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
  5. 10.Read a list of numbers and print True if the list is sorted from smallest to largest, otherwise False.Examples: 1 2 3 4 gives True1 3 2 gives False5 gives True
    Show 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
    Python
    numbers = list(map(int, input().split()))
    print(numbers == sorted(numbers))

    Output

    True

Medium-Hard

Several steps together, with filter and map.

  1. 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 9 gives [3, 5, 8, 9]1 1 1 gives [1]4 gives [4]
    Show a hint
    Build a new list: add a number only when it is not in the new list yet (solved problem 12).
    Show one possible solution
    Python
    numbers = 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]
  2. 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 3 gives 3.Examples: 4 1 7 1 3 gives 35 5 6 gives 610 9 gives 10
    Show a hint
    Find the smallest with min. Keep only the numbers that are different from it (filter, or a loop with if). The smallest of the rest is the answer (solved problem 11 does this for the largest).
    Show one possible solution
    Python
    numbers = list(map(int, input().split()))
    smallest = min(numbers)
    others = list(filter(lambda n: n != smallest, numbers))
    print(min(others))

    Output

    3
  3. 13.Read a list of numbers and print the sum of the squares of the odd numbers. Use filter and map.Examples: 1 2 3 4 5 6 gives 352 4 6 gives 07 gives 49
    Show a hint
    First choose, then change, then add: filter keeps the odd numbers, map squares them, sum adds them.
    Show one possible solution
    Python
    numbers = 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
  4. 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 1 gives [3, 5, 1, 0, 0].Examples: 0 3 0 5 1 gives [3, 5, 1, 0, 0]1 2 3 gives [1, 2, 3]0 0 0 gives [0, 0, 0]
    Show a hint
    Make a list of the numbers that are not zero. Count the zeros with count(0). Then join: others + [0] * zeros.
    Show one possible solution
    Python
    numbers = 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]
  5. 15.Read a list of numbers and rotate it k steps to the right (k is on the second line). Print the list. Example: 1 2 3 4 5 with k = 2 gives [4, 5, 1, 2, 3].Examples: 1 2 3 4 5, 2 gives [4, 5, 1, 2, 3]1 2 3, 0 gives [1, 2, 3]1 2 3, 3 gives [1, 2, 3]
    Show a hint
    One step: pop() takes the last item and insert(0, ...) puts it in front (solved problem 22). Repeat it k times with a loop.
    Show one possible solution
    Python
    numbers = 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.

Question 1

1.What does this print?

a, b = map(int, "3 4".split())
print(a + b)

Question 2

2.What does this print?

numbers = [10, 20, 30, 40]
print(numbers[-1], numbers[1:3])

Question 3

3.What does this print?

a = [1, 2]
a.append([3, 4])
print(len(a))

Question 4

4.What does this print?

fruits = ["apple", "banana", "cherry"]
x = fruits.pop()
print(x, len(fruits))

Question 5

5.What does this print?

numbers = [3, 1, 2]
numbers = numbers.sort()
print(numbers)

Question 6

6.What does this print?

a = [1, 2, 3]
b = a
b.append(4)
print(len(a))

Question 7

7.What does this print?

numbers = [3, 8, 5, 12]
total = 0
for n in numbers:
    if n % 2 == 1:
        total = total + n
print(total)

Question 8

8.Which line creates a tuple with one item?

Question 9

9.What happens when this runs?

point = (3, 5)
point[0] = 10
print(point)

Question 10

10.What does this print?

print(list(map(lambda n: n * 2, [1, 2, 3])))

Question 11

11.What does this print?

print(list(filter(lambda n: n > 2, [1, 2, 3, 4])))

Question 12

12.You have a list of prices and need a new list with 20% tax added to every price. Which tool fits?

0 of 12 answered.

13Quick summary

Quick summary
ConceptWhat it doesExample
Listordered, changeable collection[1, 2, 3]
Tupleordered, unchangeable collection(1, 2, 3)
Indexposition of an item, from 0items[0], items[-1]
Slicea part of the collectionitems[1:4], items[::-1]
append / insert / extendadd items to a listitems.append(5)
remove / pop / del / clearremove items from a listitems.pop()
index / count / insearchitems.count(3)
sort / sorted / reverseordersorted(items)
copya separate copy of a listb = a.copy()
len / sum / min / maxcalculatesum(items) / len(items)
for item in itemsgo through the itemsloop + if
enumerateindex and item togetherfor i, x in enumerate(items):
Unpackingvalues into variablesa, b = (1, 2)
split / jointext to list / list to text"a b".split()
Read two numbersone line of inputa, b = map(int, input().split())
Read a listone line of inputlist(map(int, input().split()))
mapchanges every itemmap(lambda n: n * 2, items)
filterkeeps some itemsfilter(lambda n: n > 0, items)
lambdaa small function in one linelambda n: n * 2