how to construct a list of only one tuple

Diez B. Roggisch deets at nospam.web.de
Thu Nov 27 18:12:20 EST 2008


TP schrieb:
> bearophileHUGS at lycos.com wrote:
> 
>>>>>> a=("1","2")
>>>>>> b=[("3","4"),("5","6")]
>>>>>> list(a)+b
>>> ['1', '2', ('3', '4'), ('5', '6')]
>>>>> a = ("1", "2")
>>>>> b = [("3", "4"), ("5", "6")]
>>>>> [a] + b
>> [('1', '2'), ('3', '4'), ('5', '6')]
> 
> Thanks a lot.
> Why this difference of behavior between list(a) and [a]?

Because they are different things.


list is a function that takes an iterable & creates a list out of it.

The [...] syntactic form takes a list of arguments and returns a list 
composed of them.

You see the difference maybe with this:


a = 1

foo = [a]
bar = list(a)

->

Traceback (most recent call last):
   File "/tmp/test.py", line 5, in <module>
     bar = list(a)
TypeError: 'int' object is not iterable

Diez



More information about the Python-list mailing list