  Save up to 80 % on Swift e-learning! Only this week!

# Lesson 7 - Lists in Python

In the previous tutorial, Loops in Python, we went over loops in the Python programming language. In today's lesson, we're going to introduce you all to the list data structure and show you what it's capable of accomplishing.

## Lists

Imagine that you want to store some information about multiple items, e.g. you want to keep 10 numbers in memory and each of the fields of a checkerboard or the names of 50 users. Perhaps, you have realized that there must be an easier way than to start typing in variables like user1, user2...up until user50. Aside from the fact that there may be 1000 of them, how would one go about searching for something in there?

If we needed to store a larger amount of variables of the same type, we could easily solve this problem using a list. We can imagine a list as a row of boxes, each of them containing one item. The boxes are numbered by indexes, the first one has an index of 0. (We see a list of 8 numbers on this picture)

Programming languages are very different in the way they work with lists. In some languages (especially older, compiled ones), lists had to be declared with a constant size in the source code and we weren't able to add more items to them during runtime. These sort of lists are often referred to as arrays. As we know, Python is an interpreted programming language, so it doesn't provide arrays with a fixed size. Instead, we get dynamic lists into which we can add and remove items as we please.

We use loops for the mass handling of list items.

### Declaration

We declare a list using brackets:

`numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`

Numbers is obviously the name of our variable. Now, we have a list with a size of ten ints in the variable numbers.

The list items can be accessed through brackets. Let's print the number at the first index (index 0):

`numbers = 1`

### Generating lists with range()

Filling lists manually like this would be too laborious. Let's use the `range()` function and fill a list with numbers from 1 to 10. Since range doesn't return a list but a general sequence, we'll have to convert it to list using the `list()` function.

`numbers = list(range(1, 11))`

In order to print this list, we'll use the `for` loop (as we did for printing string characters):

``````{PYTHON}

numbers = list(range(1, 11))

for number in numbers:
print(number, end = " ")``````

```Console application
1 2 3 4 5 6 7 8 9 10```

The `for` loop is also known as the `foreach` loop in some other languages. Keep in mind, that we aren't able to modify the list items using the `for` loop. There is a reference to an immutable item in the loop's variable at each step. The following code will not work:

``````{PYTHON}
# This code is wrong
numbers = list(range(1, 11))
for number in numbers:
number += 1
print(numbers)``````

The result would still be:

```Console application
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]```

### Modifying list items using range()

We only changed the values for the loop's variable, not the actual list items. If we wanted to modify the list items in a loop, we would have to use item indexes to access them:

``````{PYTHON}
numbers = list(range(1, 11))
for i in range(len(numbers)):
numbers[i] += 1
print(numbers)``````

The result would be:

```Console application
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]```

Notice the use of the `len()` function which returns the length of a list.

### String lists

Of course, we aren't limited to using numbers:

`simpsons = ["Homer", "Marge", "Bart", "Lisa", "Maggie"]`

Aside from the `range()` function, we can also use the `enumerate()` function to iterate through the list items. The advantage to it is that we'd have both the item index and the item itself:

``````{PYTHON}
simpsons = ["Homer", "Marge", "Bart", "Lisa", "Maggie"]
for i, item in enumerate(simpsons):
print("%d: %s" % (i, item))``````

The result:

```Console application
0: Homer
1: Marge
2: Bart
3: Lisa
4: Maggie```

Lists are often used to store intermediate results, which are used later in a program. If we needed a result 10x, we would calculate it once and put it into a list. Then, we'd simply read the result.

#### Slicing

It's also possible to get a slice of a list. The syntax is similar to accessing a list item. However, we specify multiple arguments like we did with the `range()` function.

Examples:

``````{PYTHON}
numbers = range(10)
print(list(numbers))
print(list(numbers[0:5]))
print(list(numbers[2:8]))
print(list(numbers[1:7:2]))
print(list(numbers[2:9:2]))``````

The result:

```Console application
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4]
[2, 3, 4, 5, 6, 7]
[1, 3, 5]
[2, 4, 6, 8]```

If the first index is not entered `e.g. list[::2]`, it assumes that it is from the beginning of the list (0). If the second index is omitted, the end of the list is assumed. Then, if the shift is not specified, it assumes that we want to step forward by 1 element.

## List methods

There are several methods for the list data type. Let's cover them.

### append()

The `append()` method appends a new item at the end of a list.

Example:

``````{PYTHON}
numbers = [2, 3, 16, 21]
numbers.append(13)
print(numbers)``````

The result:

```Console application
[2, 3, 16, 21, 13]```

### pop()

Returns the last item in a list and removes the item from the list.

Example:

``````{PYTHON}
numbers = [2, 3, 16, 21]
print(numbers.pop())
print(numbers)``````

The result:

```Console application
21
[2, 3, 16]```

### insert()

Inserts an item at a given position. The first parameter is the index and the second one is the item to be inserted at this index.

### extend()

Appends all the items from a given sequence to the list.

### clear()

Removes all the items in the list. We can achieve the same behavior by writing `del a[:]`.

### remove()

Removes a given item from the list. Throws an exception if the element is not found.

### reverse()

Reverses the elements in the list so the first element is at the last place and vice versa.

### count()

Returns how many occurrences of a given value are there in the list.

### sort()

As the name suggests, the method will sort our list. Its only parameter is the list that we want to sort. It's so clever that it works according to what we have stored in the list. Strings are sorted alphabetically, i.e. numbers depending on its value. Let's try to sort and print our Simpsons family:

``````{PYTHON}
simpsons = ["Homer", "Marge", "Bart", "Lisa", "Maggie"]
simpsons.sort()
for s in simpsons:
print(s, end = " ")``````

```Console application
Bart Homer Lisa Maggie Marge```

Try making a list of numbers and sort them. This way, you'll understand that it works for numerical datatypes as well.

### index()

The method returns the index of the first found item. If it doesn't find an item, it throws an exception, which we can't react to yet. The method takes an item as a parameter. We can specify the 2 additional numeric parameters indicating the start and the end index of the searched area. Let's allow the user to enter the name of a Simpson's character and tell them at what position he/she is stored. This exercise won't be very useful for us now since all we've got on our list are strings. However, it'll be very useful for us when we get to adding complex objects to our lists. Keep this in mind for now. Since we don't want the application to throw an error if the user enters a name which is not on our list, we'll ask whether it's present using the `in` operator like we did with substrings.

``````{PYTHON}
simpsons = ["Homer", "Marge", "Bart", "Lisa", "Maggie"]
simpson = input("Hello! What is your favorite character in the Simpsons, you may only choose from the core family members: ")
if simpson in simpsons:
position = simpsons.index(simpson);
print("If I had to rank them, that would be no. %d on my list." % (position + 1));
else:
print("Hey! That's not a Simpson!")``````

```Console application
Hello! What is your favorite character in the Simpsons (you may only choose from the core family members): Homer
If I had to rank them, that would be no. 1 on my list!```

## List functions

Python also provides global functions for working with lists. They also work for any other type of sequence.

### len()

We've already mentioned `len()`, which returns the length of a list (the total number of items in it).

### min(), max(), sum()

These are mathematical functions which return the smallest of the items (`min()`), the largest item (`max()`), and the sum of all the items (`sum()`). The methods have no parameters. We can easily calculate the average of a list's items using the `sum()` and `len()` functions.

### sorted()

This method does pretty much the same this as the `sort()` function, but it returns a sorted copy of the original list without modifying the original one.

### all()

Returns `True` if all the items are evaluated as True (non-zero numbers, non-empty strings, etc).

``````{PYTHON}
list_1 = [1, 3, 2, 0, 5]
list_2 = [6, 4, 5, 1, 2]
print(all(list_1))
print(all(list_2))``````

The result:

```Console application
False
True```

### any()

Returns `True` if there is at least one item evaluated as `True` (a non-zero number, a non-empty string, etc):

``````{PYTHON}
list_1 = [1, 3, 2, 0, 5]
list_2 = [6, 4, 5, 1, 2]
list_3 = []
print(any(list_1))
print(any(list_2))
print(any(list_3))``````

The result:

```Console application
True
True
False```

### del()

We can remove list items via so-called slicing:

``````{PYTHON}
numbers = [1, 3, 2, 0, 5]
del numbers
print(numbers)``````

The result:

```Console application
[1, 2, 0, 5]```

Alternatively, like this:

``````{PYTHON}
numbers = [1, 3, 2, 0, 5]
del numbers[1:3]
print(numbers)``````

The result:

```Console application
[1, 0, 5]```

That's enough for today, you can play with lists for a while if you'd like. In the next lesson, Strings in Python - Working with single characters, I've got a surprise for you I think you might like Article has been written for you by David Capka The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.