[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Can tuples be replaced with lists all the time?

Sam <lightaiyee at gmail.com> writes:

> My understanding of Python tuples is that they are like immutable
> lists.

That's a common expression, but I think it's not a helpful way to think
of them.

Rather, the different sequence types have different semantic purposes:

* For representing a sequence where each item means exactly the same no
  matter which position it's in (a ?homogeneous sequence?), use a list.

* For representing a sequence where the meaning of each item is strongly
  dependent on its position in the sequence (a ?heterogeneous
  sequence?), use a tuple.

See <URL:http://docs.python.org/3/library/stdtypes.html> for the
official Python description of the type differences.

> If this is the cause, why can't we replace tuples with lists all the
> time (just don't reassign the lists)? Correct me if I am wrong.

Because we need to represent different semantic concepts in our code,
and have each type support the semantics with different operations.

 \     ?I went camping and borrowed a circus tent by mistake. I didn't |
  `\      notice until I got it set up. People complained because they |
_o__)                           couldn't see the lake.? ?Steven Wright |
Ben Finney