08 - Session - Data Structures
08 - Session - Data Structures
Session 8
Data structures
2
Summary
▪ Lists
▪ Sets
3
3
Sequences
num_list = [1, 3, 5, 7, 9]
5
Lists are sequences
list1 = ["Anne", "David", "Joanna", "Andrew", "William"]
list1[0] "Anne"
list1[2] "Joanna"
list1[-1] "William"
list1[-3] "Joanna"
list1[1:3] ["David", "Joanna"]
list1[0:6:2] ["Anne","Joanna","William"]
list1[:4] ["Anne", "David", "Joanna", "Andrew"]
list1[3:] ["Andrew","William"]
list1[4:2:-1] ["William","Andrew"]
list1[:] ["Anne", "David", "Joanna", "Andrew", "William"]
list1[::-1] ["William","Andrew","Joanna","David","Anne"]
list1.remove("Andrew") ["Anne","David","Joanna","William"]
list1.pop(2) ["Anne","David","William"]
list1.append("Fernando") ["Anne","David","William","Fernando"]
list1.insert(3,"Sarah") ["Anne","David","William","Sarah","Fernando"]
list1.pop() ["Anne","David","William","Sarah"]
6
Lists: Adding new items
7
Lists: Removing items
• listName.remove(value)
• listName.pop()
• listName.pop(index)
8
Lists: sort() vs. sorted()
Write a Python program to get the total income for your top 20% of
clients once you receive a list with all the sales.
Input: [140, 200, 160, 300, 300, 20, 5, 10, 1000, 100] Output: 1300
10
Programming Challenges
11
Summary
▪ Lists
▪ Sets
12
12
Sets – Non duplicative unordered collections
Sets:
- are unordered
- are faster than lists, tuples and strings
- cannot contain duplicates
- are mutable
- are created with {}
13
Sets – Operations
14
Sets – Math Operations
my_list = [1, 1, 1, 3, 5, 7, 9]
my_set1 = set(my_list)
my_set2 = {1,9,20,40,"Pablo"}
len(my_set1)
my_set1.union(my_set2)
my_set1.intersection(my_set2)
my_set1.difference(my_set2)
my_set1.issubset(my_set2)
15
Sets – Math Operations
16
Programming Challenges
17
Programming Challenges
You work in Telefonica and the marketing department sends a list with
all the clients IDs (around 1M). How can you check if it is correct or if
you have received duplicated IDs?
18
Session Wrap-up
19
Glossary
in, not in li = […] s = {…} dict = {…}
min, max, sum list set dict
del
sorted