-2

I am trying to understand the difference between tuples and lists

I was trying to use tuples and lists in a piece of my code, and not realising the difference between tuple and list, could someone please tell me difference,

Thanks,

Gops

gops
  • 11
  • 4
  • 1
    You could simply search internet to find out. There are several articles with simple examples to explain it clearly – Extreme_Tough Jan 29 '23 at 05:11
  • A tuple is immutable. As such, it can be used as a dict key, or placed in a set. Lists cannot. There are also some implementation differences. For example, a tuple is always created with the exact size needed for the number of elements it contains, whereas lists may allocate more to allow for efficient growth. – Tom Karzes Jan 29 '23 at 05:13
  • 2
    You can read about them [here](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range). – Tom Karzes Jan 29 '23 at 05:17

1 Answers1

0

Both list and tuple are used to store multiple items within a single collection, but there is a key difference tuple is immutable while list is not. Mutability means the ability to modify the object afterward.

# Here we can modify my_list just fine
>>> my_list = ["hello"]
>>> my_list[0] = "world"
>>> print(my_list)
['world']

# But modifying my_tuple leads to an error
>>> my_tuple = ('hello',)
>>> my_tuple[0] = 'world'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> print(my_tuple)
('h', 'e', 'l', 'l', 'o')

You might think to ask why use tuples at all if we can't mutate them. Wouldn't it be better to just have everything be more flexible?

Well, there are things that tuples can do that lists cannot do such as acting as keys for a dictionary. This is a very useful trick for things like points as keys.

>>> my_dict = {("hello", "world"): "foo"}
>>> my_dict[("hello", "world")]
'foo'

If you try to do the same with lists, you get this error. The error message hints at the key difference. Lists cannot be hashed but tuples can be hashed.

>>> my_dict = {["hello", "world"]: "foo"}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
f0lie
  • 46
  • 4