Lists, tuples and dictionaries Flashcards
How do you create a new list or tuple. Give examples.
Two methods for each structure
my_list = [1,2,3] my_list2 = list([1,2,3])
my_tuple = (1,2,3) my_tuple2 = tuple([1,2,3])
strings are represented as lists or tuples?
tuples (strings are unmutable objects)
#---------------example --------------- s = 'felipe' s[0] = 'F' #This is not possible
ACCESING LIST AND TUPLE ELEMENTS
How do you acces the first element in a list or tuple? What about the last one?
my_list = list(range(10))
my_list[0] #first element
my_list[-1] #last element
How can you tell if some_value IS part of a list or tuple?
How can you tell if some_velue IS NOT part of a list or tuple?
#IS part of som_value in my_list #returns boolean
#IS NOT part of some_value not in my_list #returns boolean
this_dict = {‘k1’ : v1, ‘k2’ : v2}
(a) How do you retrieve the value corresponding to the item with key = ‘k2’?
(b) How can you check if exists an item with key = ‘some_key’?
(c) How can you check if axists an item with value = some_value?
(a) this_dict[‘k2’]
(b) ‘some_key’ in this_dict.keys() # returns boolean
(c) ‘some_value’ in this_dict.values() # returns boolean
How do you make a for loop over keys, values and items of a dictionary. Give an example.
( Consider d = {‘k1’ : v1, ‘k2’ : v2, ‘k3’ : v3} )
iterate over items
To iterate over keys and values use d.keys(), and d.values() methods.
example: for k in d.keys():
for k, v in d:
statements
SLICING
Consider the list a = list( range(100) )
(a) get the first 20 elements
(b) get the last 20 elements
(c) get the elements from index 50 to the last one
(d) get the elements in even indexes
(a) ———————
a[:20]
a[0:20]
(b) ———————
a[-20:0]
a[-20:-1]
# (c) --------------------- a[50:]
# (d) --------------------- a[::2]
RANGE
Indicate the statement to produce a range with the next characteristics:
(b) start = 0, n = 100
(a) 5, … , 20
(c) multiples of three (start = 3; end 99)
# (a) --------------------- range(101)
# (b) --------------------- range(5, 21)
# (c) --------------------- range(0:100:3)
ADDING NEW ELEMEMTS
How do you add new elements to a list, tuple, and dictionary.
(Can yu add more than one element at once?)
lists:
my_list.append(new_element)
my_list.extend([other_list]) #add a list of elements
my_list.insert(i, element)
#tuples: tricky question. tuples are unmutable objects, which means you can not add new elements.
#dictionaries some_dict[new_key] = new_value
di_2 = {new_key, new_value}
some_dict.update(di_2);
.pop( )
How is the pop method used in lists, tuples and dictionaries?
#lists: some_list.pop( ) # returns the last element of the list some_list.pop(idx) # returns the element in index = idx
#tuples: tricky question. tuples are unmutable objects, therefore they do not have a poo method
#dictionaries some_dict.popitem() # returns the last inserted item some_dicti.pop('some_key') # returns item with key = 'some_key'
REMEMBER: The pop method deletes the corresponding element/item from the list or dictionarie.
REMOVING ELEMENTS
Cosider the following list: some_list = [1, 2, 2, 2, 3, 2, 4, 5]
How can you remove all the ocurrences of the number 2?
some_list = [v for v in some_list if v != 2]
LIST COMPRENHENSION
(a) Make a list containing the numbers between 0 and 20 which are not multiples of 3.
(b) Make a list with the first 10 cubes (i.e. 1, 8, 27, …)
(a) some_list = [n for n in range(21) if n%3 != 0]
(b) other_list = [ n**3 for n in range(1:11:1) ]
FINDING ALL THE OCURRENCES
Cosider the following list of numbers:
collection = [1, 2, 2, 2, 3, 2, 4, 5]
Use the method enumerate() to find the index of all the ocurrences of number 2.
(Give a long and a short solution.)
collection = [1,2,2,2,3,2,4]
#long version def find_ocurrences(some_list, element): index_list = [] for i, value in enumerate(collection): if value == 2: index_list.append(i)
return index_list
print(find_ocurrences(collection, 2))
#short version ocurrences = [i for i, v in enumerate if v == 2]
Sorted() and Reversed()
Cosider the following list of numbers: collection = [3, 4, 2, 1, 8, 4, 5, 11, 3]
Make a list containig the same elements as collection[], but arrenged from max to min. The original list must remain unchanged.
collection = [3, 4, 2, 1, 8, 4, 5, 11, 3]
#option 1 new_list = sorted(collection, reverse = True)
#option 2 new_list = list(reversed(sorted(collection)))
ZIP
Consider the next data:
JAN FEB MAR SALES 100 80 120 COST 70 40 70
sales = [100, 80, 120] cost = [70, 40, 70]
Use zip to calculate the margin at every month. Try using list conprenhension.
method 1
sales = (100, 80, 120) cost = (70, 40, 70)
margin1 = []
for s, c in zip(sales, cost):
margin1.append(s-c)
#method 2 margin2 = [s-c for s,c in zip(sales, cost)]
Dictionaries are also known as ——- or ——-
hash maps or associative arrays
There are some students standing in a row, each of them has some number written on their back. The students are about to divide into two teams by counting off by twos: those standing at the even positions (0-based) will go to team A, and those standing at the odd position will join the team B.
Calculate the difference between the sums of numbers written on the backs of the students that will join team A, and those written on the backs of the students that will join team B.
def difference(list): A_sum = sum(list[::2]) B_sum = sum(list[1::2]) return A_sum - B_sum
toDo = [‘t1’, ‘t2’, ‘t3’, ‘t4’, ‘t5’, ‘t6’, ‘t7’, ‘t8’, ‘t9’, ‘t10’]
Given the list of task ids in your toDo list, remove each kth task from it and return the list of remaining tasks.
(a) Try using del
(b) Try using enumerate
#(a) del toDo[k-1::k]
#(b) toDo = [t for n, t in enumerate(toDo, start = 1) if n%k != 0]
Multiple level sorting
Consider a list of tuples with students info; each tuple contains the name, age, and grade (‘A’, ‘B’, ‘C’) of the student (i.e. student = (‘John’ 12 ‘B’).
Sort the students by name and by age.
Consider the list
student_tuples = [ (‘john’, ‘B’, 15), (‘jane’, ‘B’, 12), (‘dave’, ‘B’, 10), (‘john’, ‘A’, 16) ]
import operator
student_tuples = [ (‘john’, ‘A’, 15), (‘jane’, ‘B’, 12), (‘dave’, ‘B’, 10) ]
sorted(student_tuples, key= operator.itemgetter(1,2))
DICT CONSTRUCTION
Use zip to construct a dictionary like the next one:
alphabet = {‘a’ : 1, ‘b’ : 2, …, ‘z’ : 26}
#option 1: alphabet = dict(zip('abcdefghijklmnopqrstuvwxyz', range(1,27))
#option 2: alphabet = dict(zip(list(string.ascii_lowercase), range(1,27))
SET COMPRENHENSION
A pair of numbers is considered to be cool if their product is divisible by their sum. More formally, a pair (i, j) is cool if and only if (i * j) % (i + j) = 0.
Given two lists a and b, find cool pairs with the first number in the pair from a, and the second one from b.
a = [4, 5, 6, 7, 8]
b = [8, 9, 10, 11, 12]
a = [4, 5, 6, 7, 8] b = [8, 9, 10, 11, 12]
cool_pairs = {(i,j) for i in a for j in b if (i*j)%(i+j) == 0}
LIST COMPRENHENSION
Construct a multiplication table. Given an integer n, return the multiplication table of size n × n.
Example, n = 3:
multiplicationTable(n) = [[1, 2, 3],
[2, 4, 6],
[3, 6, 9,] ]
m_table = [ [i * j for i in range(1, n+1)] for j in range(1, n+1)]
DEFINING A NEW DICTIONARY
Give examples for the next three dictionary creation methods:
1- Typing items in batch 2- One item at a time 3- Using zip
# Typing items in batch d1 = {'k1' : 1, 'k2' : 2, 'k3' : 3}
# one item at a time d2 = {} d2['k1'] = 1 d2['k2'] = 2 d2['k3'] = 3
using zip
keys = (‘k1’, ‘k2’, ‘k3’)
values = (1, 2, 3)
d3 = dict(zip(keys, values))
d1, d2, d3
DICTIONARY COMPRENHENSION
Use dict comprenhension to create the next dictionaries:
d1 = {1:1, 2:2, 3:3} d2 = {1:0, 2:0, 3:0}
d1 = {k:v for k,v in zip(range(1:4), range(1,4))} d2 = {k:0 for k in range(1:4)}
DELETING ELEMENTS FROM LIST
Considers the next piece of code:
some_list = [1, 2, 2, 2, 3, 4, 2, 5]
some_list.remove(2)
What is the content of some list after executing this code?
(a) some_list = [1, 3, 4, 5]
(b) some_list = [1, 2, 2, 3, 4, 2, 5]
The remove method only deletes the first ocurrence of the corresponding element, therefore the answer is (b).
some_list = [1, 2, 2, 3, 4, 2, 5]
(Can you tell how to remove all of the ocurrences of some_element in the list?)
UPDATING LIST
some_list = [1, 2, 3, 4, 5]
How can you delete the elements 2, 3, 4 of the list.
del some_list[1:4]
COPYING A LIST
some_list = [1, 2, 3, 4, 5]
How can you copy the content of some_list[ ] to a new_list[ ]?
# option 1 new_list = some_list.copy()
# option 2 new_list = some_list[:]
COUNTING OCURRENCES OF ELEMENTS
numbers = [0, 1, 1, 2, 0, 1, 3, 4, 5, 2, 3, 6, 9, 8, 7, 1, 3]
Create a dictionary ocurrences{ } que indique el número de veces que aparece cada elemento en números[ ].
numbers = [0, 1, 1, 2, 0, 1, 3, 4, 5, 2, 3, 6, 9, 8, 7, 1, 3]
num_set = set(numbers) ocurrences = {n:numbers.count(n) for n in num_set}
MEASURING SIZE
How can you tell how many elements or items are there in a list, tuple or dictionary?
len(some_structure)
UNPACKING
parameters = (10, 100 , “cm”)
How can you assing the values stored in parameters to the variables _a, _b and _units?
parameters = (10, 100 , “cm”)
a, b, units = parameters