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

Lists

In this section, you will learn

List Basics

When programming, it is very common to use a structure that can store a number of values in a specific order. This structure has many names, such as array, list, or vector. In Python, the word list is used.

A list allows duplicates. It is also possible to have lists inside a list to create a matrix or a two-dimensional list. In Python, different elements can be of different types, which is not the case in many other languages.

We start by creating a list consisting of three fruits. To create the list, square brackets [ ] are used. Values in the list are separated by commas. Using print, we print the contents of the list.

Example

We create a list named fruits containing three strings of fruit names and print it.

fruits = ['Apple', 'Banana', 'Mango']
print(fruits)

In a list, we always start counting from zero. The first element has index 0. In the example above, we can read the first value in the list by writing fruits[0]. To read the second value in the list, we write fruits[1], and so on.

In Python, we can use negative indices to go backwards from the end. The last element is read with fruits[-1], and the second to last element is read with fruits[-2].

The fact that the first element in a list is element 0 is usually confusing for beginners. What's worse, there are programming languages where counting starts from one, although this is uncommon.

Example

How we can read values. We use the notation fruits[i] where i is the index of the element in the list.

fruits = ['Apple', 'Banana', 'Mango']
first_element = fruits[0]
second_element = fruits[1]
third_element = fruits[2]
last_element = fruits[-1]

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?

Java
Python
PHP

Adding and Removing Elements

We can write fruits = [] to create an empty list. For each list created, a number of functions are available that can be used on the list, such as append() and pop(). We write the list's name, followed by a dot, to access its functions. For example, we can write fruits.append('Pear') to add another fruit to the list. The new element is added to the end of the list.

The function pop(index) can be used to remove the element at position index from a list. For example, if we want to remove the first element in the list, we write fruits.pop(0). If we want to remove the last element, it is enough to write fruits.pop(); without an argument, -1 is used as the default index. The pop() function also returns the element that was removed, in case we want to use it.

Example

We start with an empty list, add a couple of elements, and then remove the first and last. Click run to see what the list contains at the different steps.

fruits = []
fruits.append('Apple')
fruits.append('Banana')
fruits.append('Mango') #fruits = ['Apple', 'Banana', 'Mango']

fruits.pop(0) #remove the first element, 'Apple'.
fruits.pop(-1) #remove the last element, 'Mango'.

Example

A list can contain any data type, for example, integers. Here, a list of three integers is first created. The integer 20 is added to the list, and then the second integer in the list is removed.

numbers = [10, 5, 35]
numbers.append(20)
removed = numbers.pop(1)
print('We removed the number ' + str(removed))

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?

Volvo
Tesla
Audi

It is good to know that if the list is large, it is quite inefficient to, for example, remove and add elements to the list (except at the end of the list). If this needs to be done often, there are better data structures that we will learn more about later.

List Length

To see how many elements are in a list, we can use the helper function len() with the list as an argument. This is useful, for example, if we want to loop through the entire list using while.

Example

Prints each element in the list on its own line. Also takes the opportunity to show how a list can be created with one element per line.

fun_english_words = [
    'Shenanigans', 
    'Bamboozle', 
    'Bodacious', 
    'Brouhaha', 
    'Canoodle', 
    'Malarkey'
]

count = len(fun_english_words)
index = 0
while index < count:
  print(fun_english_words[index])
  index = index + 1

In the example above, the condition to continue the loop is index < count. It is important that index never becomes as large as count. The list fun_english_words contains six elements. If we try to read outside the list when index = 6 with fun_english_words[6], the program will stop and we will get an error message.

Example

Example of an error message if we try to read outside the list. The last element is read with my_list[5]. my_list[6] results in an error message of type IndexError.

my_list = [1, 2, 3, 4, 5, 6]
print( my_list[5] ) #prints 6
print( my_list[6] ) #causes an error

Does the element exist in the list?

Using in, we can check if an element exists in the list. For example, 5 in my_list is True if 5 is in the list. We can combine this with not to check if the element is not in the list.

Example

We create a list of names and then test if a name is in the list or not. Feel free to test with other names.

the_team = ['Anton', 'Beatrice', 'Cecilia', 'David']

if 'Cecilia' in the_team:
  print('Cecilia is on the team.')

if 'Zlatan' not in the_team:
  print('Zlatan is not on the team.')
  

Test your knowledge

Below are two exercises to learn how to use lists.

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

Modify the code

The program should receive a number of integers from the user, put them in a list, and then print the sorted list. To sort the list, my_list.sort() is used.

-- Output from your program will be here --

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

Filter out positive numbers

Write a function named filter that takes a list as its only argument. Return a new list that contains only the positive integers from the original list and in the same order.

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