# list of strings
vessels = ['ABIOLA', 'ACACIA']
# list of floats
prices = [1.23, 1.98, 1.45, 1.67]
# lists of integers
quantities1 = [18, 22, 21, 32]
quantities2 = [12, 11, 16, 18]
# loop over prices
for price in prices:
print(price)
1.23 1.98 1.45 1.67
We can access individual items in a list in the following way:
prices = [1.23, 1.98, 1.45, 1.67, 2.40, 1.89]
print('The 1st price: ', prices[0] )
print('The 2nd price: ', prices[1] )
print('The 3rd price: ', prices[2] )
The 1st price: 1.23 The 2nd price: 1.98 The 3rd price: 1.45
The number inside the square brackets is the 'index' of the item. Note that Python uses 'zero indexing', so the first item in a list has an index of 0.
You can also access items 'from the end' using a negative index. So an index of -1 gives the last item, -2 gives the second last item, and so on.
print('The last price: ', prices[-1] )
print('The 2nd last price: ', prices[-2] )
The last price: 1.89 The 2nd last price: 2.4
The index can also be used to overwrite an item in the list:
print(prices)
prices[0] = 2.41
prices[-1] = 0.99
print(prices)
[1.23, 1.98, 1.45, 1.67, 2.4, 1.89] [2.41, 1.98, 1.45, 1.67, 2.4, 0.99]
You can also get a range of items from a list:
print(prices[1:4] )
[1.98, 1.45, 1.67]
This is called a 'slice'. Which indices from the prices list are included in this slice?
countries = ['USA', 'UK', 'France', 'Germany']
# adding on to the end of a list
countries.append('Spain')
print(countries)
['USA', 'UK', 'France', 'Germany', 'Spain']
# inserting into a specific index of a list
countries.insert(2, 'Australia')
print(countries)
['USA', 'UK', 'Australia', 'France', 'Germany', 'Spain']
# removing from a specific index
countries.pop(3)
print(countries)
['USA', 'UK', 'Australia', 'Germany', 'Spain']
# removing a particular value from a list
countries.remove('Germany')
print(countries)
['USA', 'UK', 'Australia', 'Spain']
primes = [2,3,5,7,11,13]
# check if a value is in a list
print(3 in primes)
print(4 in primes)
True False
# find the index of a value in a list
print(primes.index(5))
2
# find the minimum, maximum, and sum
print('minimum:', min(primes))
print('maximum:', max(primes))
print('sum:', sum(primes))
minimum: 2 maximum: 13 sum: 41
The addition and multiplication operators also work on lists:
print(quantities1 + quantities2)
print(quantities1 * 2)
[18, 22, 21, 32, 12, 11, 16, 18] [18, 22, 21, 32, 18, 22, 21, 32]
Python allows you to have lists containing multiple different types of variable, as in the below example. Try to transform this list into: [1,2,3] using the operations you've learned.