Data Structures and Looping¶
Note
Learning objectives: Differentiate lists, tuples, dictionaries, and sets. Iterate over lists, sets, dicts, tuples, and strings. Iterate with a comprehension.
>>> list_of_rodents = [ 'rabbit', 'rat', 'squirrel', 'capybara' ]
>>> for rodent in list_of_rodents:
... print rodent
...
rabbit
rat
squirrel
capybara
Iterable data structures
Class Name |
Common Name |
Meaning |
---|---|---|
list |
Array or list |
A mutable array of indexed data |
tuple |
Tuple or ordered set |
Immutable array of indexed data |
dict |
Dictionary or associative array |
Array of indexed key-value pairs |
set |
Set |
Like a set in real math with unique values |
str |
String |
It’s still a string, but it’s like an array of characters |
>>>
>>> mylist = [] # empty list
>>> myotherlist = [1, 2, 3] # list of numbers
>>> mylist
[]
>>> myotherlist
[1, 2, 3]
>>> mylist + myotherlist
[1, 2, 3]
>>> mylist.append('squirrel')
>>> mylist + myotherlist # You can add them!
['squirrel', 1, 2, 3]
>>> mylist.extend(myotherlist)
>>> mylist
['squirrel', 1, 2, 3]
>>> print(mylist[0])
squirrel
>>> mylist.append('squirrel')
>>> mylist # notice how squirrel now appears twice
['squirrel', 1, 2, 3, 'squirrel']
>>> mylist[4]
'squirrel'
>>> mytuple = tuple(mylist)
>>> mytuple # Notice the parentheses showing that this is a tuple
('squirrel', 1, 2, 3, 'squirrel')
>>> mytuple[4] # You can still grab members of it like you could from a list
'squirrel'
>>> mylist[4] = 'rat'
>>> mylist
['squirrel', 1, 2, 3, 'rat']
>>> mytuple[4] = 'rat' # A different outcome! Tuples don't change.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> mylist = [1, 2, 3, 4, 5, 6, 1, 2, 3, 4] # Notice the duplicates.
>>> mylist
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4]
>>> myset = set(mylist)
>>> myset # Notice how the duplicates are gone.
set([1, 2, 3, 4, 5, 6])
>>> myset.add(7) # Adds seven to the set.
>>> myset
set([1, 2, 3, 4, 5, 6, 7])
>>> myset.add(6) # Does nothing. Why?
>>> myset
set([1, 2, 3, 4, 5, 6, 7])
>>> mydict = {} # Empty dictionary
>>> mydict['squirrel'] = 'nuts'
>>> mydict['rat'] = 'cheese'
>>> mydict['rabbit'] = 'carrots'
>>> mydict
{'rat': 'cheese', 'squirrel': 'nuts', 'rabbit': 'carrots'}
>>> mydict['squirrel']
'nut'
>>> mydict.keys() # keys() is a special function that returns the keys of your dict
['rat', 'squirrel', 'rabbit']
>>> mydict.values()
['cheese', 'nuts', 'carrots'] # values() is a special function that returns the values of your dict
>>> for myrodent in mydict.keys():
... print(myrodent + ' prefers ' + mydict[myrodent])
...
rat prefers cheese
squirrel prefers nuts
rabbit prefers carrots