Remember
tuple() constructs an immutable sequence from an iterable. Its elements can still refer to mutable objects.
tuple() constructs an immutable sequence from an iterable. Its elements can still refer to mutable objects.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
items = [3, 2]
values = tuple(items)
print(values)Top-level scope
[3, 2]Object 2 · tuple(3, 2)tuple() constructs an immutable sequence from an iterable. Its elements can still refer to mutable objects.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
items = [3, 2]
values = tuple(items)
print(values)
|
v
DISPLAYED RESULT
(3, 2)
FINAL BINDINGS
items --> object 1 (list)
values --> object 2 (tuple)
object 1: [3, 2]
object 2: (3, 2)Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
items = [3, 2]
values = tuple(items)
print(values)Top-level scope
[3, 2]Object 2 · tuple(3, 2)The example has finished. Compare the final output with the values and references above.
(3, 2)
What do you expect this program to print?
items = [3, 2]
values = tuple(items)
print(values)tuple() FunctionThe tuple() function in Python is used to create an immutable ordered collection of elements called a tuple. Tuples are similar to lists, but they cannot be changed after creation.
tuple(iterable)
iterable – (Optional) Any iterable like a list, string, set, or dictionary.my_list = [1, 2, 3]
result = tuple(my_list)
print(result)
(1, 2, 3)
text = "abc"
result = tuple(text)
print(result)
('a', 'b', 'c')
my_dict = {'a': 1, 'b': 2}
result = tuple(my_dict)
print(result)
('a', 'b')
Note: Only the keys are included in the resulting tuple.
empty = tuple()
print(empty)
()
tuple = () and then using tuple() will cause an error (do not overwrite built-ins).() with tuple creation – remember, () alone is empty tuple, (5) is just a number, use (5,) to create a one-element tuple.In interviews, tuples are often used when returning multiple values from functions, or for storing coordinates, RGB values, etc.
tuple() converts an iterable into a tuple.tuple(); one-item tuple: (item,).Convert the following list into a tuple, and then try to change one value. What happens?
numbers = [10, 20, 30]
t = tuple(numbers)
print(t)
# Try this:
# t[0] = 99 # What error do you get?
Connect what you noticed in the example with the idea below.
tuple() constructs an immutable sequence from an iterable. Its elements can still refer to mutable objects.
A tuple guarantees that every object it contains is immutable.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.