Log in to save your progress.
<< Previous
Home
Next >>
Note! The window is too narrow to use Pythonlab.dev. Use a device with a keyboard!

Reference

Click on a function to read more.
Basics part 1
Syntax
Short description
break
break interrupts code that is repeated
continue
continue interrupts a repetition and starts the next
elif
elif is a combination of else and if
else
else can be used last in an if-statement
float()
Converts to type float (decimal number)
if
if controls the code to do different things depending on a condition
input()
Receives input from the user
int()
Converts to type int (integer)
randint()
Generates a random integer
round()
Rounds a number
str()
Converts to type string
while
while is used to repeat code
Basics part 2
Syntax
Short description
abs
Absolute value
append
Adds an element to a list
def
Defines a function
for
for is used to repeat code
len
Returns the number of elements in an object
max
Returns the largest element
min
Returns the smallest element
pop
Removes an element from a list
return
Returns data from a function
sum
Sums the elements in an object

More about lists

In this section you will learn to

Sublists or part of a string

In Python, it is easy to create a sublist of a list or a substring of a string. In English, it is called slicing. The syntax used is variable[start:end] where start is the index where the part begins and end is where the part ends. The index end is not included.

Example

Some examples of how the syntax can be used to create a substring.

today = '2026-04-19'
year = today[0:4] # index 0 to 3
month = today[5:7] # index 5 and 6
day = today[8:10] # index 8 and 9

Example

Sublists are created in the same way as substrings. Remember that the first element in the list has index 0.

# the list shows times in the Olympic final in Tokyo for men's 100 meters.
times = ['9.80', '9.84', '9.89', '9.93', '9.95', '9.95', 'DNF', 'DQ']

times_1_3 = times[0:3] # the three best times in a sublist
times_4_6 = times[3:6] # the times in places 4 to 6

Login or create an account to save your progress and your code.

What does the code do?

Read the code below and try to figure out what the program prints. Run the program after you answer and see if you were correct.

-- Output from your program will be here --

Question: What will the program print?

nty
nty P
ty P
ty Py

More ways to slice

In the syntax variable[start:end] it is possible to omit start or end. Yes, it is actually possible to omit both to include everything. If start is omitted, everything from the beginning up to end is included. If end is omitted, everything from start to the end is included.

Example

Examples of slicing where start index and end index are omitted.

s = 'Monty Python'

# Include characters from the beginning up to index 5
beginning = s[:5]

# Include characters from index 6 to the end
end = s[6:]
  

Do you remember that negative indices can be used in lists and strings? Negative indices mean that we count the position from the end, -1 means the last element. It is also possible to use negative indices when creating substrings and sublists.

Example

Create a sublist with negative indices.

s = 'Monty Python'
substring = s[1:-1] #do not include the first and last character
  

Login or create an account to save your progress and your code.

What does the code do?

Read the code below and try to figure out what the program prints. Run the program after you answer and see if you were correct.

-- Output from your program will be here --

Question: What will the program print?

Monty Pyth Mo
Monty Pyth M
Monty Pytho Mo
Monty Pytho M

List comprehensions

List comprehensions are used to create lists by writing only one line of code. The English name for list comprehensions is list comprehension and is probably what you will encounter most. List comprehensions combine the syntax for creating a list [] with the syntax for a for-loop. Later we will see that it is possible to use an if-statement as well, but we start with simpler examples.

Example

Creates a list with five identical elements.

my_list = [0 for i in range(5)]

In the example above, the counter i was never used. We see what happens if we use i instead of zero.

Example

More examples of list comprehensions.

list_1 = [i for i in range(5)] # [0,1,2,3,4]

list_2 = [i*5 for i in range(5)] # [0,5,10,15,20]
  

Now we will see how we can use an if-statement inside a list comprehension. This can, for example, be used to filter out elements in a list.

Example

List comprehension with if-statement.

names = ['Maria', 'Anna', 'Margareta', 'Elisabeth', 'Eva', 'Kristina']

#create a new list with names ending in a
ends_with_a = [n for n in names if n[-1] == 'a']

#list with names that are at most five characters long
short_names = [n for n in names if len(n) <= 5]

List comprehensions can be a bit tricky to understand, especially if you know another programming language that doesn't have them. If you have a list comprehension [x for x in list if x < 10] then you can think of it like this: Insert element x into the list for all elements x in list where x is less than 10. So we create a new list from list with all elements less than 10.

List comprehensions are not necessary to know because it is always possible to do the same thing with a regular for-loop or while-loop. But for experienced Python programmers who often work with lists, it is a nice feature.

Login or create an account to save your progress and your code.

Change the code

Change the code so that the list comprehension filters out all negative numbers.

-- Output from your program will be here --

A list of lists

Imagine a regular list and then imagine that each element in that list is a new list. It is a list of lists or 2D list.

A 2D list is especially suitable for models of something in two dimensions. A common image is a good example. To iterate through all the elements in a 2D list, a nested for-loop is usually used.

Example

Create a 2D list with two rows and three columns. The two elements in the list represent rows. These elements are in turn also lists.

list_2d = [ [1, 2, 3], [4, 5, 6] ]

Example

The variable image is a 2D list that represents a simple image. Each pixel is either # or a space. The image has seven pixels in width and six pixels in height. The 2D list thus has six rows and each row contains seven columns. We print the image with a nested for-loop.

A real image works in the same way. However, the elements are usually a number that describes the color of that pixel.

image = [
    [' ', '#', '#', ' ', '#', '#', ' '],
    ['#', ' ', ' ', '#', ' ', ' ', '#'],
    ['#', ' ', ' ', ' ', ' ', ' ', '#'],
    [' ', '#', ' ', ' ', ' ', '#', ' '],
    [' ', ' ', '#', ' ', '#', ' ', ' '],
    [' ', ' ', ' ', '#', ' ', ' ', ' ']
]

for row in image: #
    for column in row:
        print(column, end='')
    print() #new line in the output for each printed line in the image
  

Login or create an account to save your progress and your code.

Create

Sum all numbers in the variable image using a nested loop and print the sum.

-- Output from your program will be here --
Status
You have finished all tasks in this section!
🎉