Do not name variables after classes. In your example, you do this both with list
and tuple
.
You can rewrite as follows:
lst = ['a', 'b']
tup = tuple(lst)
lst.append('a')
another_tuple = tuple(lst)
Explanation by line
- Create a list, which is a mutable object, of 2 items.
- Convert the list to a tuple, which is an immutable object, and assign to a new variable.
- Take the original list and append an item, so the original list now has 3 items.
- Create a tuple from your new list, returning a tuple of 3 items.
The code you posted does not work as you intend because:
- When you call
another_tuple=tuple(list)
, Python attempts to treat your tuple
created in the second line as a function.
- A
tuple
variable is not callable.
- Therefore, Python exits with
TypeError: 'tuple' object is not callable
.