Converting list to tuple in Python

Question:

>>> list=['a','b']
>>> tuple=tuple(list)
>>> list.append('a')
>>> print(tuple)
('a', 'b')
>>> another_tuple=tuple(list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Why cannot I convert the list ‘list’ to a tuple?

Asked By: rooni

||

Answers:

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

  1. Create a list, which is a mutable object, of 2 items.
  2. Convert the list to a tuple, which is an immutable object, and assign to a new variable.
  3. Take the original list and append an item, so the original list now has 3 items.
  4. 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.
Answered By: jpp