Python Lists
In Python, a list is an ordered collection of elements. It's a type of array that can contain heterogeneous data of various types, such as numerical and alphanumeric values.
list = [element1, element2, element3, ... ]
What's the difference between lists and variables?
Both lists and variables have a name, but a variable can hold only one piece of data. In contrast, a list can store multiple pieces of data.
How to create a list in Python
You assign a name to the list just like you would with a variable.
After the equals sign, you write the ordered collection of data within square brackets, separated by commas.
year = [2010, 2011, 2012]
In Python, square brackets [ ] distinguish lists from other types of arrays such as tuples, sets, and dictionaries.
A list can contain heterogeneous data of different types.
For example, the following list includes both numerical and alphanumeric values.
[2010, 2011, 2012, 2013, 'leap year']
A list can also contain other nested lists and even libraries.
[2010, 2011, 2012, 2013, ['leap year', 'non-leap year']]
How to display a list
To display the elements of a list, use the list's name in the PRINT statement.
print(year)
The result on the screen will be:
[2010, 2011, 2012]
To display a single element from the list, you need to specify the position of the element within square brackets.
print(year[2])
In this case, the interpreter will display only the content of that specific element.
2012
The first element of the list is at position zero [0].
How to find out the number of elements in a list
To find out the number of elements in a list, use the len function.
len(listname)
The len function returns a positive integer that indicates the size of the list, i.e., the number of elements it contains.
A practical example
Given the following list:
year = [2010, 2011, 2012]
To get the size of the list, you write:
print(len(year))
The command returns the number of elements in the list, which is three (3).
3
In this case, I printed the result on the screen.
However, you could use this information for many other useful purposes.
For example, as the upper limit of a loop.
i = 0
while i < len(year):
print(year[i])
i = i + 1
How to modify list elements
To modify a list, you assign new values to its elements.
Example
Given the following list:
year = [2010, 2011, 2012, 2013]
To change the first element, you type:
year[0] = 2009
Now the list is:
[2009, 2011, 2012, 2013]
To modify a group of elements, you use slicing.
Instead of a single index, you specify the start and end positions of the elements.
year[0:2] = [2008, 2009]
After the modification, the list becomes:
[2008, 2009, 2012, 2013]
And so on.