7

In Python, the List is one type of homogeneous sequences, while the Tuple is one type of heterogeneous sequences. But in a List, we still can put arbitrary type of data in it, like a=[1, 2, 'abc']. So, what's the real difference between homogeneous and heterogeneous sequences in Python?

injoy
  • 3,993
  • 10
  • 40
  • 69
  • 2
    Both lists and tuples can contain instances of different types. The main difference between them is that tuples are immutable. Where did you read lists were homogeneous sequences in Python? – Frédéric Hamidi Jul 20 '13 at 17:52
  • @FrédéricHamidi It says that in the docs. – arshajii Jul 20 '13 at 17:53
  • 3
    I've downvoted this because python lists are not in fact homogenous. – Marcin Jul 20 '13 at 17:54
  • 3
    @Marcin: I'm not sure that's an appropriate reason for a downvote. – Dietrich Epp Jul 20 '13 at 17:55
  • @FrédéricHamidi, it comes up in section [tuples and sequences](http://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences): *Tuples are immutable, and usually contain an **heterogeneous** sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually **homogeneous** and are accessed by iterating over the list.* – miku Jul 20 '13 at 17:55
  • 2
    @FrédéricHamidi I made a mistake. In the document, it says that "Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list." I missed the word "usually" here. You're right, thanks. – injoy Jul 20 '13 at 17:56

1 Answers1

10

Lists and tuples are mostly identical in Python, except that lists are mutable and tuples are immutable. Both lists and tuples can be either homogeneous or heterogeneous.

If you want sequences with enforced homogeneity, use the array module or use NumPy, for example.

Documentation

From the Python Documentation for sequence types:

Lists are mutable sequences, typically used to store collections of homogeneous items (where the precise degree of similarity will vary by application).

Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the enumerate() built-in). Tuples are also used for cases where an immutable sequence of homogeneous data is needed (such as allowing storage in a set or dict instance).

Community
  • 1
  • 1
Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
  • Lists and tuples should not be used interchangeably in most circumstances, while your answer seems to imply the contrary. – arshajii Jul 20 '13 at 17:57
  • 3
    @arshajii: I was very careful to limit my answer to facts about the sequences themselves. This is not an appropriate place to opine about which type is better. – Dietrich Epp Jul 20 '13 at 17:59