qr code

Python lists

Python lists

You can make a shorter list in Python by writing the list elements separated by a comma between square brackets.

Running the code

squares = [1, 4, 9, 16, 25]
letters = ['a', 'b', 'c']
print(squares)
print(letters)

you will see this output

[1, 4, 9, 16, 25]
['a', 'b', 'c']

The element in a list with \(n\) elements, are numbered with indices from \(0\) to \(n-1\). You get an element of a list by writing the name of the list followed by the index of the element between square brackets.

Running the code

squares = [1, 4, 9, 16, 25]
letters = ['a', 'b', 'c']
print(squares[0])
print(letters[2])

you will see this output

1
c

If you try to use an index not between \(0\) to \(n-1\), you will get an execution error. As an example, the code print(letters[3]) would not work.

The function len()

The function len(<arg>) returns the number of elements of the list you pass as argument. The function can also be used to find the number of symbols in a string.

Running the code

squares = [1, 4, 9, 16, 25]
country = "Sweden"
print("There are", len(squares), "squares in the list.")
print(country, "has", len(country), "letters.")
print("The last square is", squares[len(squares)-1])

you will see this output

There are 5 squares in the list.
Sweden has 6 letters.
The last square is 25

The last index of the list squares is len(squares)-1, hence the code squares[len(squares)-1] will give us the last square. This construction to find the last element of a list is used in many programming languages. In Python you can get the last element by instead using a negative index.

Negative indices

If you use a negative index to get an element of a list, it is counted from the end of the list. The index -1 is the last element, the index -2 is the second element from the end, etc.

Running the code

squares = [1, 4, 9, 16, 25]
print("The last square is", squares[-1])

you will see this output

The last square is 25

Slice

You can get a part of a list by using the operator : between square brackets after the name of the list. The resulting part of the list is called a slice.

If we use the list name squares, you can make a slice in three ways.

  • squares[i:] makes a slice with elements from index i to the end of the list.
  • squares[i:j] makes a slice with elements from index i to index j. The element with index j is not included.
  • squares[:j] makes a slice for all elements from the beginning of the list to index j. The element with index j is not included.

Running the code

squares = [1, 4, 9, 16, 25]
print(squares[3:])
print(squares[1:3])
print(squares[:3])
print(squares[1:-1])

you will see this output

[16, 25]
[4, 9]
[1, 4, 9]
[4, 9, 16]

The last call of print() makes a slice of all elements but the first and the last.

The operator : can also be used on strings. The code

country = "Sweden"
print(country[:2])
print(country[2:4])
print(country[4:])

yields the output

Sw
ed
en

List methods

There are a number of methods for lists that are written using dot notation after the name of the list. Some of these methods are shown here on the list lst

method explanation
lst.append(x) append x to the end of the list
lst.remove(x) remove the first occurrence of x
lst.index(x) returns the index of the first occurrence of x
lst.insert(k, x) insert x at position k in the list
lst.clear() remove all elements
lst.reverse() reverse the order of the elements
lst.sort() sort the elements in ascending order

Running the code

squares = [1, 4, 9, 16, 25]
squares.reverse()
print(squares)
countries = ["Sweden", "Denmark", "Norway"]
print(countries)
print("Denmark has index", countries.index("Denmark"))
countries.append("Finland")
print(countries)

you will see this output

[25, 16, 9, 4, 1]
['Sweden', 'Denmark', 'Norway']
Denmark har index 1
['Sweden', 'Denmark', 'Norway', 'Finland']

For more list methods see Python: More on lists.

Add lists

If you have two lists you can make a third list by adding the two lists. Running the code

lst1 = ["Sweden", "Denmark", "Norway"]
lst2 = ["Finland", "Iceland"]
lst3 = lst1 + lst2
print(lst3)

you will see this output

['Sweden', 'Denmark', 'Norway', 'Finland', 'Iceland']

You can add lists even if they have elements of different data types. Running following code

lst1 = ["Sweden", "Denmark", "Norway"]
lst2 = [17, -9, 2]
lst3 = lst1 + lst2
print(lst3)

you will see this output

['Sweden', 'Denmark', 'Norway', 17, -9, 2]

The operator in

We have seen the operator in used on the function range() in for statements. The operator can also be used to see if an element is in a list.

Running the code

lst = [9, 5, 2]
print(3 in lst)
print(5 in lst)

you will see this output

False
True

The operator in can be used in a for statement to iterate over all elements of a list.

Running the code

lst = [9, 5, 2]
for number in lst:
  print(number)

you will see this output

9
5
2

The operator in can also be used in a for statement to iterate over all characters of a string.

Running the code

str = "Hello"
for char in str:
  print(char)

you will see this output

H
e
l
l
o

Create lists

You can create a list from an iteration by first creating an empty list, and then add an element at the time in a loop. As an example, the list [2, 7, 12, 17, 22] can be created using following code

lst = []
for i in range(5):
  lst.append(2+5*i)
print(lst)

Using Python, there is a shorter way to create lists called list comprehension. To create the list above using list comprehension, you use following code

lst = [2+5*i for i in range(5)]
print(lst)

You can use list comprehension to create a list of characters taken from a string. Running the code

country = "Sweden"
lst = [char for char in country]
print(lst)

you will see this output

['S', 'w', 'e', 'd', 'e', 'n']
Example 1

Run the code

lst = [i for i in range(100)]
print(lst, sep=" ")

Remove all numbers from the list that are divisible by five, by adding the code:

for number in lst:
  if number%5 == 0:
    lst.remove(number)

and print the result.

You can also use list comprehension to create a list of elements, taken from another list, if some condition holds. The condition works as a filter for choosing elements. As an example, we can create the list of all numbers less than 100 that are not divisible by five, using following code:

lst = [i for i in range(100) if i%5 != 0]
print(lst, sep=" ")
list comprehension

can be used with or without a "filter".

new_list = [<expression(i)> for i in old_list]
new_list = [<expression(i)> for i in old_list if <some_filter(i)>]

The variable name i could be any variable name.

Sum, min and max

The built-in functions min() and max() can either be used for at least two numerical arguments, as in

print(min(6, 10, 2, -5))
print(max(6, 10, 2, -5))
-5
10

or with an argument that is a list, as in

lst = [i**2 for i in range(10)]
print(min(lst))
print(max(lst))
0
81

The built-in function sum() can be used with a list as argument. The combination of using list comprehension and the built-in function sum(), provides an easy and short way of calculating sums.

lst = [i**2 for i in range(10)]
print(sum(lst))
285

The function join()

If you have a list where every element is a string, you can use the function <separation>.join(<some_list>) to concatenate all list elements to a string, where the elements are separated by some string of your own choice. The function call should be preceded by the string you want as a separator, followed by a dot.

Running the code

countries = ["Sweden", "Denmark", "Norway"]
countries1 = "-".join(countries)
countries2 = "".join(countries)
print(countries1)
print(countries2)

you will see this output

Sweden-Denmark-Norway
SwedenDenmarkNorway

If you want to make a string of a list containing numbers, you can cast the numbers to strings. Running following code:

numberlist = [5, 7, 3]
str1 = "-".join(str(number) for number in numberlist)
str2 = "".join(str(number) for number in numberlist)
print(str1)
print(str2)

you will see this output

5-7-3
573

The function split()

With the function <some_string>.split(<separation>), you can split a string into parts that are put in a list. If you don't use an argument to call split(), the parts will be separated by a blank.

Following code separates the parts of the string by a comma, and then by a blank:

str1 = "Sweden, Denmark, Norway"
str2 = "Island Finland"
lst1 = str1.split(",")
lst2 = str2.split()
print(lst1)
print(lst2)

The resulting output is:

['Sweden', ' Denmark', ' Norway']
['Island', 'Finland']

If you want to split a string of numbers that are separated in some way, and put the numbers in a list; then you can use following code that converts to int and float respectively:

integers = "6,9,14"
lst1 = [int(number) for number in integers.split(",")]
print(lst1)
floats = "3.14 2.5 -9.7"
lst2 = [float(number) for number in floats.split()]
print(lst2)

The output is:

[6, 9, 14]
[3.14, 2.5, -9.7]

Copy lists

If you try to make a copy of a list, using a regular assignment, the code will act in a perhaps surprising way. With following code, a copy of a list is made using an assignment, then the content of the original list is changed. The copy will also be changed.

lst1 = [2+5*i for i in range(4)]
lst2 = lst1
print("lst1 = ", lst1)
print("lst2 = ", lst2)
lst1[2] = -5
print("lst1 = ", lst1)
print("lst2 = ", lst2)

The output is:

lst1 =  [2, 7, 12, 17]
lst2 =  [2, 7, 12, 17]
lst1 =  [2, 7, -5, 17]
lst2 =  [2, 7, -5, 17]

In order to understand this behavior, it helps to think of how lists are stored. A list is stored in a number of cells in the CPU (Central Processing Unit) register. A large list takes up many cells.

lists refers to cells

When lst2 is assigned lst1, both variables will refer to the same cells. Since lst1 could be very large, the assignment does not copy the content of very many cells to new cells.

If you want to make a copy where new cells will be used, you can use the function <some_list>.copy().

The code

lst1 = [2+5*i for i in range(4)]
lst2 = lst1.copy()
print("lst1 = ", lst1)
print("lst2 = ", lst2)
lst1[2] = -5
print("lst1 = ", lst1)
print("lst2 = ", lst2)

yields the output:

lst1 =  [2, 7, 12, 17]
lst2 =  [2, 7, 12, 17]
lst1 =  [2, 7, -5, 17]
lst2 =  [2, 7, 12, 17]

Random order

In the module random there is a function shuffle() that shuffles the elements in a list, in a way resembling shuffling cards.

In order to use shuffle(), you must first import it from random.

Following code

from random import shuffle

lst = [2*i for i in range(6)]
print(lst)
shuffle(lst)
print(lst)

results in this output

[0, 2, 4, 6, 8, 10]
[4, 10, 2, 0, 6, 8]

where the last line of the output shows a random order of the list elements. A new random order will be generated each time the code is run.

Exercises

Exercise 1

List of names

Make a list with of names. Choose what names you want in the list.

  1. Let the user write a name and then show if the name was in the list or not.
  2. Change the code so the user can remove a name from the list. If the name given by the user is in the list, remove it and then print the list. Otherwise show some sort of message.
  3. Change the code so the user can add a name to the list. Add the name, print the resulting list and then print the number of names in the list.

Exercise 2

Create lists

Use list comprehension to create following three lists:

  • [6, 10, 14, 18, 22]
  • [9, 4, -1, -6]
  • [-1.5, -1.7, -1.9, -2.1, -2.3, -2.5]

Exercise 3

Find file extension

Make a program that lets the user write a file name, including the file extension. A file name like that could be "paper.docx", "image.png", or "test.min.js" (a minified Javascript file).

Your program should then output the file extension. Use the function split().

Running the code may look like this:

Write a file name: paper.docx
File extension: docx

or like this:

Write a file name: test.min.js
File extension: js

Exercise 4

Handle dates

The 23rd of June 1996 is written as 06231995, using the date format mmddyyyy used in the US. In Sweden this date is written as 19950623, using the date format yyyymmdd.

  1. Let the user write a date using the US date format. Use the operator : (slice) to find the year, month and date, then print these values.

    Running the code may look like this:

    Enter a date (mmddyyyy): 06231995
    year: 1995
    month: 06
    day: 23
  2. Write the date given by the user in Swedish date format.

  3. When comparing dates, the Swedish date format is slightly easier to use. Add code that compares the date given by the user with 1st of January 2000. Then print whether the user date is in this or the previous millennium.

Exercise 5

Find sums

Use list comprehension and the built in function sum() for following exercises.

  1. Find the sum of the first 1000 numbers of the harmonic progression

    \[1, \frac{1}{2}, \frac{1}{3}, \frac{1}{4}, \ldots.\]
  2. Find the sum of the first 1000 numbers of the geometric progression

    \[1, \frac{1}{2}, \frac{1}{4}, \frac{1}{8}, \ldots.\]

Exercise 6

Create list from input

Use the function split() for following exercises.

  1. Let the user write names separated by blanks. Put the names in a list and print it. Running the program may look like this:

    Write names separated by blanks: Tom Ellen Kim
    ['Tom', 'Ellen', 'Kim']
  2. Let the user write integers separated by blanks. Put the numbers in a list of integers. Print the list. Sort the list. Print the list again. Running the program may look like this:

    Write numbers: 9 7 13 6
    [9, 7, 13, 6]
    [6, 7, 9, 13]

Exercise 7

Find the mean value

Let the user write a number of decimal numbers separated by blanks. Put the numbers in a list of floats.

Define a function that takes a list as argument and returns the mean value of the numbers in the list. Use the function on the numbers entered by the user and print the mean value.

Running the program may look like this:

Write decimal values: 3.5 8.8 13 7.2 6.5
The mean value = 7.8

Exercise 8

Find the median

Let the user write a number of decimal numbers separated by blanks. Put the numbers in a list of floats.

Define a function that takes a list as argument and returns the median value of the numbers in the list. Handle the two cases that the list has an odd number of elements, and an even number of elements. Use the function on the numbers entered by the user and print the mean value.

Running the program may look like this:

Write decimal values: 3.5 8.8 13 7.2 6.5
The median = 7.2

Exercise 9

Practice the seven time tables

Make a program that lets the user practice the seven time tables. The program should ask what seven multiplied by \(x\) is for every integer \(1\le x \le 10\), but in a random order. Use a list and the function shuffle() from the module random. Print whether an answer was correct or not. Keep score of the correct answers. Print the total number of correct answers after the user has answered all ten questions.

Exercise 10

Random groups

Make a list of names. The names could be students in a class.

Define a function make_groups(students, max_size) that has two parameters, a list students and an integer max_size.

The function make_groups should start by writing the total number of students and the maximum group size. After that, the ordering of the students should be shuffled and printed, one student per row. First see to it that this code works.

If the maximum group size is three, then every third row of students should be preceded by the group number. If the maximum group size is four, this should happen every fourth row, and so on. Use an if statement and the remainder from integer division to achieve this.

Call the function make_groups using the list you made as first argument, and a suitable number for the maximum group size as second argument.

Running the program may look like this:

11 students
Maximum group size 3
------------
Group 1
    Mia
    Maria
    Kim
Group 2
    Albert
    Olga
    Anna
Group 3
    Mohammed
    Olivia
    Agnes
Group 4
    Lucas
    Eve

Exercise 11

Convert from decimal to binary

This exercise is a more advanced version of Exercise 6 on the side Python loops: Exercises.

  • Let the user write a positive integer.
  • Use repeated integer division (quotient/remainder) to store the digits of the binary number in a list in reverse order.
  • Reverse the order of the list.
  • Convert the elements of the list to a string. Print the string.

Running the program may look like this:

Write a positive integer: 210
As a binary number it is written like this: 11010010

Exercise 12

The sieve of Eratosthenes

The sieve of Eratosthenes is an algorithm for finding prime number. The algorithm was invented in ancient Greece and is still used. The algorithm works like this for primes less than a hundred:

Make a list of all integers between 2 and 100.

Choose the first number in the list (the number 2). Remove all numbers after this position that are divisible by 2.

Eratosthenes1 Eratosthenes2

Choose the second number in the list (the number 3). Remove all numbers after this position that are divisible by 3.

Eratosthenes3 Eratosthenes4

Choose the third number in the list (the number 5). Remove all numbers after this position that are divisible by 5.

Eratosthenes5 Eratosthenes6

Repeat this until you get to the end of the list.

Implement the sieve of Eratosthenes in Python. You will need two nestled loops, i.e. one loop inside another loop.

You will need two variables to step through the loops. One variable to keep track of the blue position in the images, and one for the red positions.

In the inner loop, the list will become shorter, hence the variable keeping track of red positions may refer to an index that is too large. When checking divisibility, you can also check that the index is valid. If the variable pos is used for the blue position and index for the red, you can use following if statement:

if index < len(lst) and lst[index]%lst[pos] == 0:
	lst.remove(lst[index])

When a condition like this is checked, it is checked from left to right. If the leftmost expression is false, the next expression is never executed, since the condition must be false. Hence, the rightmost expression will never be executed if index is too large.

End your program by printing the list. The list looks like this:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

When your code works, you can generate all prime numbers between 2 and 1000. There are 168 such primes.