5

Is the List in python homogeneous or heterogeneous?

David Hall
  • 32,624
  • 10
  • 90
  • 127
Sivanagaiah
  • 153
  • 3
  • 10
  • 9
    Homogeneous. All the elements have to be objects – John La Rooy Mar 01 '11 at 06:05
  • @gnibbler It's a deceitful answer. I would downvote if it was possible. – eyquem Mar 01 '11 at 08:22
  • [12,45,89,103,4879] is an homogenous list. In fact, your question is not well expressed; you should have written: "may a list be heterogenous ?" and have precised under what criterion the homo/hetero-genous aspect is appreciated. – eyquem Mar 01 '11 at 08:45
  • 3
    @eyquem: `It's a deceitful answer. I would downvote if it was possible.` That seems a bit harsh. Why do you think this answer is deceitful? It is 100% correct AFAK. If the elements in a Python list are not objects, what are they in Python speak? – dawg Mar 02 '11 at 20:47
  • http://existentialtype.wordpress.com/2011/03/19/dynamic-languages-are-static-languages/ – Wes Jan 03 '13 at 01:20
  • Warning: Resurrecting this pedantically. In an interview in 2003, the BDFL himself called list elements heterogeneous. There's not a much more authoritative source than that. Reference: http://www.artima.com/intv/speed3.html. – Taylor D. Edmiston Nov 04 '13 at 05:08

6 Answers6

25
>>> def a(): pass
>>> lst=[1,'one',{1:'one'},a,[1,1],(1,),True,set((1,))]
>>> for each in lst:
...    print type(each), str(each)
... 
<type 'int'> 1
<type 'str'> one
<type 'dict'> {1: 'one'}
<type 'function'> <function a at 0x100496938>
<type 'list'> [1, 1]
<type 'tuple'> (1,)
<type 'bool'> True
<type 'set'> set([1])

Any questions?

the wolf
  • 34,510
  • 13
  • 53
  • 71
  • 2
    +1 but for a beginner, this example would be clearer if you declared lst=[1,'1','one',{1:'one'},a] then iterated it in two separate lines. – dkamins Mar 01 '11 at 05:56
  • @carrot-top. Yes , a question. Considering that all the object have the same structure (a type, a value), you mean that the list is homogenous,as gnibbler and pynator, don't you ? :) – eyquem Mar 01 '11 at 08:56
  • @eyquem: Great question. Python *lists* are homogenous actually. The list data type holds ordered muteable lists of Python [objects](http://effbot.org/zone/python-objects.htm). Python objects are heterogeneous, objects can contain arbitrary amounts and kinds of data. All data in Python are objects. Object data can hold scalars like ints, floats, complex data structures like dicts, tuples and other lists. Most items in the language are also objects, and lists can hold an ordered list of these objects. – the wolf Mar 01 '11 at 16:02
  • 2
    @carrot-top _" Python lists are homogenous actually"_ Do you realize that it's exactly the contrary of what your above answer seems to express. A beginner will understand nothing after reading of all this ... list of posts – eyquem Mar 01 '11 at 20:52
  • 1
    @eyquem: `Do you realize that it's exactly the contrary of what your above answer seems to express.` It is not contrary at all. Lists are an ordered, homogeneous, muteable collection of Python objects; objects in Python can be almost anything at all. Since Python objects are various types, a homogeneous list of various types can appear heterogeneous. You just need to truly *grok* what a Python object refers to: almost anything that is actionable... – the wolf Mar 02 '11 at 03:35
  • http://existentialtype.wordpress.com/2011/03/19/dynamic-languages-are-static-languages/ – Wes Jan 03 '13 at 01:19
  • I was curious about how Python 2's sorting rules work, so I [looked it up](https://github.com/python/cpython/blob/2.5/Objects/object.c#L739). Basically if the types are not normally sortable, it defaults to these rules: `None` is smaller than everything. Then come numbers, and then compare based on type names. If they're the same name or incomparable numbers (e.g. `complex` and 'int'), fail to sort. – Alyssa Haroldsen Jan 21 '17 at 00:37
9

Lists in Python can be heterogeneous, but by the general convention it is preferable that they only contain homogeneous elements. Python tuples are the natural data structure for heterogeneous sequences.

Of course you can argue that both tuples and lists are just homogeneous sequences of Python objects, but that is a misleading oversimplification and doesn't add any value.

Since tuples are immutable and lists are mutable you could also argue that mutability is the real distinction between them. However, that is not how they were intended. More on this can be found in this question.

Community
  • 1
  • 1
nikow
  • 21,190
  • 7
  • 49
  • 70
  • _Lists are meant to be iterated over, tuples are meant to be accessed by position_. A tuple's elements are an ordered sequence, and it's usual for the ordering to convey semantic information. A list's elements, being primarily a predictably iterable collection, will normally at least support the same interface (unless you want to start coding type-checking loops, which are often bad style). With the introduction of `collections.NamedTuple` it became obvious that numerical indexing of tuples was less readable. – holdenweb Sep 22 '16 at 15:50
8

The List in Python is heterogeneous - the same list can accept objects of various different types.

There is a snippet here which gives you a homogeneous list in Python. No idea how that piece of code would perform however.

David Hall
  • 32,624
  • 10
  • 90
  • 127
5

Please try a simple

a=[1, "a"]

and see if it throws an error before asking a question.

Btw, it does not.

Michael Schubert
  • 2,726
  • 4
  • 27
  • 49
1

One more argument for homogeneity of lists: the PEP 484 and the new typing module. The items of tuple can be individually typed with Tuple:

Tuple, used by listing the element types, for example Tuple[int, int, str]. The empty tuple can be typed as Tuple[()]. Arbitrary-length homogeneous tuples can be expressed using one type and ellipsis, for example Tuple[int, ...]. (The ... here are part of the syntax, a literal ellipsis.) [reference]

>>> import typing
>>> typing.Tuple[str, int, float]
typing.Tuple[str, int, float]

However a list, via typing.List only accepts a single type parameter:

List, used as List[element_type]

>>> typing.List[str, int, float]
Traceback (most recent call last):
  ...
TypeError: Too many parameters for typing.List<~T>; actual 3, expected 1
0

It depends if you talk about the direct elements of a list or its indirect elements.

I believe that a list is in reality a list of references, not of objects, and that when the interpeter has to use a list, it knows that in fact it must manipulate the objects to which the references are pointing, not the references themselves: that's the "execution model" of Python, I think.

  • What I call indirect element of a list are the objects that constitute the value of the list.

  • What I call direct elements are the references to these objects that constitutes the implementation of the list.

So:

  • considered as a list of references, a list is homogenous: all the elements are variables, in the plain sense of variable = chunk of memory whose value can change (while the value of an object never changes)

  • considered as a list of the objects pointed by the references, a list is heterogenous. The innuendo being that their TYPES are heterogenous.

That's my understanding. I don't know if I am fully right.

eyquem
  • 26,771
  • 7
  • 38
  • 46
  • 1
    Be careful with the "list of references" or pointer based mental model of objects in Python. See [this discussion](http://effbot.org/zone/call-by-object.htm) on why Python neither passes by reference or value; it passes by object. The same holds for lists. They are an ordered, muteable, iterable collection of objects. Objects are different than "references" which implies pointers. – the wolf Mar 01 '11 at 16:14
  • @carrot-top Thank you to be interested by this subject. First, I don't understand why you evoke the passing or arguments to functions while I was here above describing how I understand the data model and the execution model of Python. Secondly, I had already read your cited page of effbot, and its link to another page by Fredrik Lundh. I confess that I understand only a little bit of what they speaks about. I am not at my ease with the meaning they give to the word 'object'. It seems that they melt diverse meaning and as a result I understand nothing and find their explanations unclear – eyquem Mar 01 '11 at 21:24
  • `I am not at my ease with the meaning they give to the word 'object'.` Without a clear understanding of "object" as used by Python, you will be very confused by many of the concepts of the language. It is core concept. `I don't understand why you evoke the passing or arguments to functions...` The discussion regarding *objects* is germane to the understanding of lists as a collection of objects. – the wolf Mar 02 '11 at 03:31