Python Data Structures
Built in Types
Today we will be talking about some other built in types in
python!
• Lists
• Tuples
• Sets
• Dictionaries
Terms We'll Use
Here is some vocab we'll be using in today's lecture:
• Data structure-A way of organizing or storing information.
So far, the main data structure we've seen is the list.
• Ordered-The data structure has the elements stored in an
ordered sequence
• Mutable-The contents of the data structure can be
changed.
Lists
An ordered group of items
Does not need to be the same type
Could put numbers, strings or donkeys in the same list
List notation
A = [1,”This is a list”, c, Donkey(“kong”)]
Methods of Lists
•List.append(x)
– adds an item to the end of the list
•List.extend(L)
–Extend the list by appending all in the given list L
•List.insert(I,x)
–Inserts an item at index I
•List.remove(x)
–Removes the first item from the list whose value is x
Examples of other methods
•a = [66.25, 333, 333, 1, 1234.5] //Defines List
– print a.count(333), a.count(66.25), a.count('x') //calls method
–2 1 0 //output
•a.index(333)
–//Returns the first index where the given value appears
–1 //ouput
•a.reverse() //Reverses order of list
–a //Prints list a
– [333, 1234.5, 1, 333, -1, 66.25]//Output
•a.sort()
–a //Prints list a
–[-1, 1, 66.25, 333, 333, 1234.5] //Output
Tuples
Tuples are ordered, immutable collections of elements.
The only difference between a tuple and a list is that once a
tuple has been made, it can't be changed!
Tuples
Making a tuple:
a = (1, 2, 3)
Accessing a tuple:
someVar = a[0]
The syntax for access is exactly like a list. However, you can't
reassign things.
Tuples So Far
We've already used tuples without knowing it!
def myFunc():
return 1, 2
def main():
result = myFunc()
print(result)
When you return multiple things and store it in a single
variable, it comes back as a tuple!
Tuples So Far
Why would you want a tuple?
Sometimes it's important that the contents of something not
be modified in the future.
Instead of trying to remember that you shouldn't modify
something, just put it in a tuple! A lot of programming is
learning to protect you from yourself.
Sets
A set is an unordered collection of elements where each
element must be unique. Attempts to add duplicate elements
are ignored.
Sets
Creating a set:
mySet = set(['a', 'b', 'c', 'd'])
Or:
myList = [1, 2, 3, 1, 2, 3]
mySet2 = set(myList)
Note that in the second example, the set would consist of the
elements {1, 2, 3}
Sets
Things we can do with a set:
mySet = set(['a'])
# Add an element:
mySet.add('b')
#Remove an element:
mySet.remove('b')
# Remove and return a random element:
mySet.pop()
Sets
There is also support for combining sets.
Returns a new set with all the elements from both sets:
mySet.union(someOtherSet)
Returns a new set with elements that were in both sets:
mySet.intersection(someOtherSet)
Tons more methods can be found here:
https://docs.python.org/3/tutorial/datastructures.html
Dictionaries
Up until now our storage has been done in lists.
Lists can be viewed as a structure that map indexes to values.
If I make the list:
myList = ['a', 'b', 'c']
I have created a mapping from 0 to 'a', 1 to 'b', and so on.
If I put in 0, I'll get 'a' back.
Dictionaries
Dictionaries let use whatever kind of keys we want!
Instead of having 1 correspond to 'b', I can have "hello"
correspond to 'b'.
Before: Now I can do things like:
0 'a' "Hello" 'a'
1 'b' 1 'b'
2 'c' 3.3 'c'
Dictionaries
This looks exactly like you'd expect!
myDict = {}
myDict["hello"] = 'a'
myDict[1] = 'b'
myDict[3.3] = 'c'
print(myDict["hello"])
Prints:
'a'
Dictionaries
Imagine you have a bunch of university students, and you're
storing their grades in all their classes.
Use a dictionary to look up grades by name:
student = "Clark Kent"
grades = ["A","B","C","D","D","C"]
gradeDict = {}
gradeDict[student] = grades
print( gradeDict["Clark Kent"] )
Dictionaries
When you look up something in a dictionary, the thing you're
putting in (like the index in a list) is called a key. What we get
out is called a value. A dictionary maps keys to values.
myDict["hello"] = 10
^ ^
Key Value
Dictionaries
Just like in a list, if you do this:
myDict["hello"] = 10
myDict["hello"] = 11
print(myDict["hello"])
Prints:
11
Dictionaries
If we want to get just the keys, or just the values, there's a
function for that!
listOfKeys = myDict.keys()
listOfValues = myDict.values()
listOfPairs = myDict.items()