The Python List

In [139]:
# Create a list of countries in Europe
europe = ['France', 'England', 'Germany', 'Spain']
In [140]:
# Print countries in Europe
print(europe)
['France', 'England', 'Germany', 'Spain']
In [141]:
# Access the items of a list with [index]
print(europe[0])
print(europe[1])
print(europe[2])
print(europe[3])
France
England
Germany
Spain
In [142]:
# Change the item value in a list by refering to its index
europe[0] = 'Italy'
print(europe)
['Italy', 'England', 'Germany', 'Spain']
In [143]:
# How many countries in Europe? (length of Europe)
print('There are', len(europe), 'countries in', europe)
There are 4 countries in ['Italy', 'England', 'Germany', 'Spain']
In [144]:
# Check if France is in Europe
'France' in europe
Out[144]:
False
In [145]:
# How to add another country to Europe
europe.append('France')
print(europe)
['Italy', 'England', 'Germany', 'Spain', 'France']
In [146]:
# Check again if France is in Europe
'France' in europe
Out[146]:
True
In [195]:
# How to add more than one country to Europe at the same time
europe.extend(['Scotland', 'Northern Ireland'])
print(europe)
['Italy', 'Germany', 'France', 'England', 'Scotland', 'Northern Ireland']
In [147]:
# How to sort a list in ascending order
europe.sort()
print(europe)
['England', 'France', 'Germany', 'Italy', 'Spain']
In [148]:
# How to sort a list in descending order?
europe.sort(reverse=True)
print(europe)
['Spain', 'Italy', 'Germany', 'France', 'England']
In [149]:
# How to remove spain from europe?
europe.remove( 'Spain')
print(europe)
['Italy', 'Germany', 'France', 'England']