3. Lists
● A list is an object that holds a collection of objects; it represents a
sequence of data. In that sense, a list is similar to a string, except a
string can hold only characters.
● A list can hold any Python object. A list need not be homogeneous;
that is, the elements of a list do not all have to be of the same type.
3
7. Functions and Methods for Lists
● There are several built-in functions that operate on lists. Here are
some useful ones:
● For example, the following computes the average of the values in a
list L:
●average = sum(L)/len(L)
7
9. Adding Items
• Need to use method
• List.Append( new_item )
• List.Insert(Index_Position, new_item)
• Does not needs to be next in sequence
• Updating values
• List[ index ] = new_value
10. Searching Items
• for item_to_search IN list_values
• List.index(item_to_search)
• ValueError if not found
• List.count(item_to_search)
• Occurences of item in list
11. Concatenation / Multiplier
• List.extend(other_list)
• Adds other_list to end of of List
• +=
• Same as above
• List_Values * num_of_times_to_repear
13. Sorting
• List.sort()
• Key, reverse
• Sorted( any_iterable)
• Key, reverse
• Difference
• changes current vs returns new
14. Functions and Methods for Lists
● Important note There is a big difference between list methods and
string methods: String methods do not change the original string, but
list methods do change the original list.
● To sort a list L, just use L.sort() and not L=L.sort(). In fact, the latter
will not work at all.
14
16. Tuples
● A tuple is essentially an immutable list. Below is a list with three elements and a
tuple with three elements:
● Tuples are enclosed in parentheses, though the parentheses are actually
optional.
● Indexing and slicing work the same as with lists.
● As with lists, you can get the length of the tuple by using the len function, and,
like lists, tuples have count and index methods.
● However, since a tuple is immutable, it does not have any of the other methods
that lists have, like sort or reverse, as those change the list.
16
L = [1,2,3]
t = (1,2,3)
17. Tuples
● One reason why there are both lists and tuples is that in situations where speed
really matters, tuples are generally faster than lists.
● The flexibility of lists comes with a corresponding cost in speed.
● To convert an object into a tuple, use tuple.
● The following example converts a list and a string into tuples:
17
t1 = tuple([1,2,3])
t2 = tuple('abcde')
18. Packing / Unpacking Tuples
• To extract values of tuples
• Variable, after variable = tuple( first_item, item2 )
• * unpacks tuple to function arguments
• Create functions that return tuples
20. Sets, as in Mathematical Sets
• in mathematics, a set is a collection of objects, potentially of many
different types
• in a set, no two elements are identical. That is, a set consists of
elements each of which is unique compared to the other elements
• there is no order to the elements of a set
• a set with no elements is the empty set
21. Creating a set
Set can be created in one of two ways:
•constructor: set(iterable) where
the argument is iterable
my_set = set('abc')
my_set {'a', 'b', 'c'}
•shortcut: {}, braces where the elements
have no colons (to distinguish them from
dicts)
my_set = {'a', 'b','c'}
22. Diverse elements
• A set can consist of a mixture of different types of
elements
my_set = {'a',1,3.14159,True}
• as long as the single argument can be iterated through,
you can make a set of it
23. no duplicates
• duplicates are automatically removed
my_set = set("aabbccdd")
print(my_set)
{'a', 'c', 'b', 'd'}
24. common operators
Most data structures respond to these:
• len(my_set)
• the number of elements in a set
• element in my_set
• boolean indicating whether element is in the set
• for element in my_set:
• iterate through the elements in my_set
25. Set operators
• The set data structure provides some special operators that
correspond to the operators you learned in middle school.
• These are various combinations of set contents
• These operations have both a method name and a shortcut binary
operator
26. method: intersection, op: &
a_set=set("abcd") b_set=set("cdef")
a_set & b_set {'c', 'd'}
b_set.intersection(a_set) {'c', 'd'}
e f
a b c d
28. method: union, op: |
a_set=set("abcd") b_set=set("cdef")
a_set | b_set {'a', 'b', 'c', 'd', 'e', 'f'}
b_set.union(a_set) {'a', 'b', 'c', 'd', 'e',
'f'}
a b c d e f
29. method: symmetric_difference, op: ^
a_set=set("abcd"); b_set=set("cdef")
a_set ^ b_set {'a', 'b', 'e', 'f'}
b_set.symmetric_difference(a_set) {'a', 'b',
'e', 'f'}
e f
a b c d
30. method: issubset, op: <=
method: issuperset, op: >=
small_set=set("abc"); big_set=set("abcdef")
small_set <= big_set True
bit_set >= small_set True
a b c d e f
31. Other Set Ops
• my_set.add("g")
• adds to the set, no effect if item is in set already
• my_set.clear()
• emptys the set
• my_set.remove("g") versus
my_set.discard("g")
• remove throws an error if "g" isn't there. discard doesn't
care. Both remove "g" from the set
• my_set.copy()
• returns a shallow copy of my_set
33. What is a dictionary?
• In data structure terms, a dictionary is better termed an associative
array, associative list or a map.
• You can think if it as a list of pairs, where the first element of the pair,
the key, is used to retrieve the second element, the value.
• We map a key to a value
34. Key Value pairs
• The key acts as an index to find the associated value.
• Just like a dictionary, you look up a word by its spelling to find the
associated definition
• A dictionary can be searched to locate the value associated with a key
• Key must be immutable
• strings, integers, tuples are fine
• lists are NOT
• Value can be anything
35. Dictionaries
● To declare a dictionary we enclose it in curly braces, {}.
● Each entry consists of a pair separated by a colon.
● The first part of the pair is called the key and the second is the value.
● The key acts like an index.
● Here is a simple dictionary:
● So in the first pair, 'A':100, the key is 'A', the value is 100, and d['A'] gives 100.
● Keys are often strings, but they can be integers, floats, and many other things as
well. You can mix different types of keys in the same dictionary and different
types of values, too.
35
d = {'A':100, 'B':200}
36. Functions and Methods for Dictionaries
● To change d['A'] to 400: d['A']=400
● To add a new entry to the dictionary, we can just assign it, like below: d['C']=500
● To delete an entry from a dictionary, use the del operator: del d['A']
● To copy a dictionary, use its copy method. Here is an example: d2 = d.copy()
● The empty dictionary is {}, which is the dictionary equivalent of [] for lists or '' for
strings.
36
d = {'A':100, 'B':200}
37. Functions and Methods for Dictionaries
● The dict function is another way to create a dictionary.
d = dict([('A',100),('B',300)])
● This creates the dictionary {'A':100,'B':300}. This way of building a
dictionary is useful if your program needs to construct a dictionary
while it is running.
37
38. Dictionary content methods
• my_dict.items() – all the key/value pairs
• my_dict.keys() – all the keys
• my_dict.values() – all the values
There return what is called a dictionary view.
• the order of the views corresponds
• are dynamically updated with changes
39. Views are iterable
for key in my_dict:
print key
• prints all the keys
for key,value in my_dict.items():
print key,value
• prints all the key/value pairs
for value in my_dict.values():
print value
• prints all the values