Site icon Meccanismo Complesso

Python Lessons – 2.7 Lists

Python Lessons - 2.7 Lists m
Python Lessons - 2.7 Lists

Lists

In the Python language, lists are a type of object. This particular type of object is used to store a series of values in an indexed sequence.

A list is defined when using a sequence of values enclosed within square brackets,

>>> lista = [1, 1, 2, 3, 5, 8, 13, 21]

and to access its values it is sufficient to write the name (like all the other variables).

>>> lista
[1, 1, 2, 3, 5, 8, 13, 21]

In case you want to access only one of the values of the list, for example the third one, you will write the name and the corresponding index which is 2 (and not 3 !!!! the indexes in Python start from 0).

>>> lista[2]
2

It is possible to create an empty list and then fill it afterwards during the program execution.

>>> nuova_lista = []
>>> nuova_lista
[]

A list can also contain values of different types, including other lists.

>>> misto = [1, 3.14, "Hello", [1,2,3]]
>>> misto
[1, 3.14, "Hello", [1,2,3]]

List of lists

In Python there are no multidimensional arrays (matrices) and therefore lists are used to represent them.

>>> matrice = [[1,2,3],[4,5,6],[7,8,9]]

In this case, to access an element of an internal list, two indices must be called, the first referred to the general list, the second referred to the internal list.

>>> matrice[1][2]
6

IndexError

A very common mistake is the request for an index beyond those defined. In this case we have an IndexError.

>>> a = [0,1,2,3]
>>> a[6]
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
a[6]
IndexError: list index out of range

Strings as lists

Another curiosity is that so far we have used strings. Well these strings can be considered lists of characters

>>> a = "Hello World!"
>>> a[6]
'W'

⇐ Go to Python Lesson 2.6 – WHILE loop

Go to Python Lesson 2.8 – Operations on list ⇒

Exit mobile version