Laboratory No
Laboratory No
COLLEGE OF ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
City of Malolos Bulacan
1
Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their
content:
>>> cubes = [1, 8, 27, 65, 125] # something's wrong here
>>> 4 ** 3 # the cube of 4 is 64, not 65!
64
______________________
>>> cubes[3] = 64 # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]
______________________
You can also add new items at the end of the list, by using the append() method.
>>> cubes.append(216) # add the cube of 6
>>> cubes.append(7 ** 3) # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]
______________________
Assignment to slices is also possible, and this can even change the size of the list or clear it
entirely:
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
______________________
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
______________________
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
______________________
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]
______________________
The built-in function len() also applies to lists:
>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4
______________________
It is possible to nest lists (create lists containing other lists),
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
______________________
>>> x[0]
['a', 'b', 'c']
______________________
>>> x[0][1]
'b'
____ __________________
2. EXERCISES
What does the following code print?
lst = []
nums = [15, 6]
2
lst.append(nums)
nums = [10, 30, 20]
lst.append(nums)
lst.sort()
print lst
3.