Unit3 2
Unit3 2
5
4
for i in [5, 4, 3, 2, 1] :
3
print ( i )
2
print ('Blastoff!’)
1
Blastoff!
Lists and definite loops - best pals
>>> x = list()
>>> print (type(x))
>>> <type 'list'>
>>> print(dir(x))
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort’…etc]
>>>
Building a list from scratch
• We can create an empty
list and then add >>> stuff = list()
elements using the >>> stuff.append('book')
append method >>> stuff.append(99)
• The list stays in order and >>> print (stuff)
new elements are added ['book', 99]
at the end of the list >>> stuff.append('cookie')
>>> print (stuff)
['book', 99, 'cookie']
Using extend on list
Split breaks a string into parts produces a list of strings. We think of these as
words. We can access a particular word or loop through all the words.
Deleting elements
There are several ways to delete elements from a list. If you know the index of the element
you want, you can use pop:
Pop modifies the list and returns the element that was removed. If you don’t provide an
index, it deletes and returns the last element.
Deleting elements
If you don’t need the removed value, you can use the del operator:
If you know the element you want to remove (but not the index), you can
use remove:
To remove more than one element, you can use del with a slice index:
Aliasing
If a refers to an object and you assign b = a, then both variables refer to the same object:
The association of a variable with an object is called a reference. In this example, there
are two references to the same object.
An object with more than one reference has more than one name, so we say that the
object is aliased.
A Story of Two Collections..
• List
• A linear collection of values that stay in order
• Dictionary
• A “bag” of values, each with its own label
Dictionaries
tissue
calculator
perfume
money
candy
Dictionaries
• Dictionaries are Python’s most powerful data collection
• Dictionaries allow us to do fast database-like operations in Python
• Dictionaries have different names in different languages
• Associative Arrays - Perl / Php
• Properties or Map or HashMap - Java
• Property Bag - C# / .Net
Dictionaries
• A dictionary is like a list, but more general. In a list, the indices have
to be integers; in a dictionary they can be (almost) any type.
• A dictionary contains a collection of indices, which are called keys,
and a collection of values.
• Each key is associated with a single value. The association of a key and
a value is called a key-value pair or sometimes an item.
• In mathematical language, a dictionary represents a mapping from
keys to values, so you can also say that each key “maps to” a value.
• As an example, we’ll build a dictionary that maps from English to
Spanish words, so the keys and the values are all strings.
Dictionaries
• The function dict creates a new dictionary with no items. Because dict
is the name of a built-in function, you should avoid using it as a
variable name.
• >>> eng2sp = dict()
• >>> eng2sp
• {}
• The squiggly-brackets, {}, represent an empty dictionary.
• To add items to the dictionary, you can use square brackets:
• >>> eng2sp['one'] = 'uno'
• This line creates an item that maps from the key 'one' to the value
'uno'
Dictionaries
• If we print the dictionary again, we see a key-value pair with a colon
between the key and value:
• >>> eng2sp
• {'one': 'uno'}
• This output format is also an input format.
• you can create a new dictionary with three items:
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres’}
• But if you print eng2sp, you might be surprised:
• >>> eng2sp
• {'one': 'uno', 'three': 'tres', 'two': 'dos'}
• The order of the key-value pairs might not be the same.
Dictionaries
• Lists index their entries >>> purse = dict()
based on the position in >>> purse['money'] = 12
the list >>> purse['candy'] = 3
• Dictionaries are like bags - >>> purse['tissues'] = 75
no order >>> print purse
{'money': 12, 'tissues': 75, 'candy': 3}
• So we index the things we
put in the dictionary with >>> print (purse['candy’])
a “lookup tag” 3
>>> purse['candy'] = purse['candy'] + 2
>>> print purse
{'money': 12, 'tissues': 75, 'candy': 5}
Comparing Lists and Dictionaries
• Dictionaries are like Lists except that they use keys instead of
numbers to look up values
counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names :
if name not in counts:
counts[name] = 1
else :
counts[name] = counts[name] + 1
print counts
>>> l = list()
>>> dir(l)[
'append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
>>> t = tuple()
>>> dir(t)
['count', 'index']
Tuples are more efficient
• Since Python does not have to build tuple structures to be
modifiable, they are simpler and more efficient in terms of memory
use and performance than lists.
A B
A B
A B
A B