Tuples and Lists
Jump to navigation
Jump to search
Creating tuples
A tuple is a sequence of elements that cannot be modified. They are useful to group elements of different type.
t = ('bananas','200g',0.55)
Creating lists
A list is a sequence of elements that can be modified. In many cases, all elements of a list will have the same type.
l = ['apples',
'bananas',
'oranges']
Accessing elements of lists and tuples
Using square brackets, any element of a list and tuple can be accessed. The first character has the index 0.
l = [1,2,3,4]
print l[0] # first
print l[3] # last
print l[-1] # last
l[0] = 'kiwi' # assigning an element
Creating lists from other lists
Lists can be sliced by applying square bracketsin the same way as substrings.
l = [0,1,2,3,4,5]
print l[1:3] # [1,2]
print l[0:2] # [0,1]
print l[:3] # [0,1,2]
print l[-2:] # [4,5]
m = l[:] # creates a copy!
List functions
l[0] = 'kiwi' # assigning an element
Adding elements to a list:
l.append(5) # adds at the end
Removing elements from a list:
l.remove(3)
l.pop() # removes last element
Sorting a list
l.sort()
Count elements:
l.count(3)