## Lists, Sequences and Unpacking

### Lists

Python’s basic container type is the list. You will learn about containers in the next module.

We can define our own list with square brackets:

[1, 3, 7]


[1, 3, 7]

type([1, 3, 7])


list

Lists do not have to contain elements of just one type:

various_things = [1, 2, "banana", 3.4, [1,2] ]


We access an element of a list with an int in square brackets (its index).

Note that list indices start from zero.

one = 1
two = 2
three = 3

my_new_list = [one, two, three]


We can directly access the middle value in the list

middle_value_in_list = my_new_list[1]

middle_value_in_list


2

Alternatively

[1,2,3][1]


2

Other examples of accessing list elements:

various_things[2]


‘banana’

index = 2
various_things[index]


‘banana’

We can use a string to join together a list of strings:

name = ["John", "Philip", "Idra", "Doe"]
print(" -> ".join(name))


John -> Philip -> Idra -> Doe

And we can split up a string into a list:

"Ernst Stavro Blofeld".split("o")


[‘Ernst Stavr’, ‘ Bl’, ‘feld’]

And combine these:

"->".join("John Ronald Reuel Tolkein".split(" "))


‘John->Ronald->Reuel->Tolkein’

A matrix can be represented by nesting lists – putting lists inside other lists.

identity = [[1, 0], [0,1]]

identity[0][0]


1

… but later we will learn about a better way of representing matrices.

#### Ranges

Another useful type is range, which gives you a sequence of consecutive numbers. In contrast to a list, ranges generate the numbers as you need them, rather than all at once.

If you try to print a range, you’ll see something that looks a little strange:

range(5)


range(0, 5)

We don’t see the contents, because they haven’t been generated yet. Instead, Python gives us a description of the object - in this case, its type (range) and its lower and upper limits.

We can quickly make a list with numbers counted up by converting this range:

count_to_five = list(range(5))
print(count_to_five)


[0, 1, 2, 3, 4]

Ranges in Python can be customised in other ways, such as by specifying the lower limit or the step (that is, the difference between successive elements). You can find more information about them in the official Python documentation.

### Sequences

Many other things can be treated like lists. Python calls things that can be treated like lists sequences.

A string is one such sequence type, and can be indexed in the same way as a list.

Sequences support various useful operations, including:

* Accessing a single element at a particular index: sequence[index]
* Accessing multiple elements (a slice): sequence[start:end_plus_one]
* Getting the length of a sequence: len(sequence)
* Checking whether the sequence contains an element: element in sequence


The following examples illustrate these operations with lists, strings and ranges.

print(count_to_five[1])


1

print("James"[2])


m

We can print specific elements:

print(count_to_five[1:3])
print("Hello World"[4:8])


[1, 2]

o Wo

Note that the last element in the range given is not acted upon. For ranges we start at the first element indexed, then all elements up to but not including the second element.

print(len(various_things))
print(len("Python"))


5

6

‘len’ returns the number of elements in a sequence.

In the following example the list contains two elements; a list and an integer.

len([[1, 2], 4])


2

In these examples we are checking for the presence of specified items in a sequence.

In the first statement we are making the assertion: The string “John” is ‘in’ the sequence ‘name’

If the assertion is correct, ‘True’ is returned, else ‘False’ is returned.

print("John" in name)
print(9 in count_to_five)


True

False

### Unpacking

Multiple values can be unpacked when assigning from sequences, like dealing out decks of cards.

mylist = ['Goodbye', 'Cruel']
a, b = mylist
print(a)


Goodbye

The elements of the list are dealt to ‘a’ and ‘b’ in turn.

This is the same as:

a = mylist[0]
b = mylist[1]


If there is too much or too little data, an error results:

zero, one, two, three = range(7)


—————————————————————————

ValueError Traceback (most recent call last)

in () </span>

—-> 1 zero, one, two, three = range(7)

ValueError: too many values to unpack (expected 4)

zero, one, two, three = range(2)


————————————————————————–

ValueError Traceback (most recent call last)

in () </span>

ValueError: not enough values to unpack (expected 4, got 2)

Python provides some handy syntax to split a sequence into its first element (“head”) and the remaining ones (its “tail”):

head, *tail = range(4)
print("tail is", tail)


tail is [1, 2, 3]

Note the syntax with the *. The same pattern can be used, for example, to extract the middle segment of a sequence whose length we might not know:

one, *two, three = range(10)

print("one is", one)
print("two is", two)
print("three is", three)


one is 0

two is [1, 2, 3, 4, 5, 6, 7, 8]

three is 9