Tuples Flashcards

1
Q

What is a tuple? How are they used? How are they different from lists?

A

Tuples are an ordered sequence of items similar to lists.

They are used with parenthesis rather than square brackets, and with commas. A tuple with a single entry is written as (x, )

Tuples are immutable while lists are. This means that the item reference address cannot change once a tuple is created, like strings. This makes tuples more safe than lists. They are also processed faster, and can be stored more compactly than lists. We can also unpack tuples successfully since you know how many items are in them (immutability).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Explain the process of unpacking a tuple

A

Take the example:

record = (“Joe”, 19, “CIV”)
The values on the right are “packed” together in a tuple. To unpack them, assign the values on the right to variables:

name, age, studies = record
name
“Joe”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Explain Tuples as return values

A

Functions can only return a single value, but by making the value a tuple, we can effectively group together as many values as we like (packing) and return them together

def area_circumference(radius):
“””
(float) -> float, float
Return the circumference and area of a circle of a specified radius.
“””
circumference = 2 * math.pi * radius
area = math.pi * radius * radius

return (circumference, area) We can also unpack the output: circumference, area = area_circumference(radius)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Explain 2 ways you can use tuples and lists together

A

1 - Placing lists in a tuple. You won’t be able to change each entire list since they are items in a tuples, but can change the items in each lists. Refer to week 8 lecture 1.

2 - Placing tuples in a lists. If you have multiple tuples, you can place them in square brackets to create a large list. This allows you to change each entire tuple because they are now items in the list. However, you cannot change the inside of each tuple. Refer to week 8 lecture 1.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly