Chapter 12: Tuples Flashcards
Lists are “ “ while tuples are “ “
Lists are mutable while tuples are immutable
What is the following action called?
tuple(“Safari”)
(‘S’, ‘a’, ‘f’, ‘a’, ‘r’, ‘i’)
Unpacking
What will happen in the following code?
num = (1, 2, 3, 4)
a, *b, c = num
print(a, b, c)
Adding * to b will create a list in the middle section.
»>print(a, b, c)
1 [2, 3] 4
How do you delete an item in a tuple?
You can’t. Tuples are immutable. You can, however, delete the entire tuple using the del tuple method.
I want to count how many times the number 3 shows up in the below tuple. How can I do this?
tuple1 = (1, 2, 3, 4, 3, 3, 3, 3, 66)
By using the count function.
»> tuple.count(3)
4
What if I want to find the max number listed in a tuple?
Use the max function.
»> tuple1 = (1, 4, 90, -177, 43)
»> max(tuple1)
90
How could I change a list to a tuple?
Using the tuple(list) method
»> my_list = [1, 2, 3, 4]
»> my_list = tuple(my_list)
»> my_list
(1, 2, 3, 4)
Consider the below code:
»> my_tuple = ([“Hello”, “World”], [“It’s”, “nice”])
Can we edit the list in this tuple?
Yes. By using append or remove.
»> my_tuple[0].append(“hello”)
»>print(my_tuple)
([“Hello”, “World”, “hello”], [“It’s”, “nice”])
or
»> my_tuple[0].remove(“hello”)
»>print(my_tuple)
([“Hello”, “World”], [“It’s”, “nice”])
What will the output be for the following code?
»> my_tuple = ([“Hello”, “World”], [“It’s”, “nice”])
»> my_tuple.append([‘x’, ‘y’, ‘z’])
print(my_tuple)
You will receive an attribute error. Since we are trying to modify the tuple and not the list we will get the following: AttributeError: ‘tuple’ object has no attribute to ‘append’
” “ is a built-in function that takes two or more sequences and returns a list of tuples where each tuple contains one element from each sequence.
zip
I want a sequence of tuples where each tuple is a key-value pair, how would I accomplish this? Hint: dictionary method
By using items which returns a sequence of tuples
tuple is a key-value pair.
»> d = {‘a’:0, ‘b’:1, ‘c’:2}
»> t = d.items()
»> t
dict_items([(‘c’, 2), (‘a’, 0), (‘b’, 1)])
True or False
Can you use a list of tuples to initialize a dictionary?
True
»> t = [(‘a’, 0), (‘c’, 2), (‘b’, 1)]
»> d = dict(t)
»> d
{‘a’: 0, ‘c’: 2, ‘b’: 1}
In some context, like a “ “ statement, it is syntactically simpler to create a tuple than a list.
return
Lists, dictionaries and tuples are examples of what?
data structures
An assignment with a sequence on the right side and a tuple of variables on the left. The right side is evaluated and then its elements are assigned to the
variables on the left.
tuple assignment