19

How can I append the content of each of the following tuples (ie, elements within the list) to another list which already has 'something' in it? So, I want to append the following to a list (eg: result[]) which isn't empty:

l = [('AAAA', 1.11), ('BBB', 2.22), ('CCCC', 3.33)]

Obviously, the following doesn't do the thing:

for item in l:
    result.append(item)
    print result

I want to printout:

[something, 'AAAA', 1.11] 
[something, 'BBB', 2.22] 
[something, 'CCCC', 3.33]
budi
  • 6,351
  • 10
  • 55
  • 80
DGT
  • 2,604
  • 13
  • 41
  • 60
  • 1
    Do you want _all_ the tuples to be appended to the list, one after another? Or only one at a time? In other words, are you looking for one list containing `[something, tuple1, tuple2, tuple3]`, or several lists, `[something, tuple1]`, `[something, tuple2]`, and `[something, tuple3]`? – David Z Jul 18 '10 at 03:50
  • The title is misleading, since based just on the title the answer would be `result.extend(item)` instead. – user2340939 Jan 11 '22 at 12:37

4 Answers4

44
result.extend(item)
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
5

You can convert a tuple to a list easily:

>>> t = ('AAA', 1.11)
>>> list(t)
['AAAA', 1.11]

And then you can concatenate lists with extend:

>>> t = ('AAA', 1.11)
>>> result = ['something']
>>> result.extend(list(t))
['something', 'AAA', 1.11])
John
  • 1,143
  • 7
  • 10
3

You can use the inbuilt list() function to convert a tuple to a list. So an easier version is:

l = [('AAAA', 1.11), ('BBB', 2.22), ('CCCC', 3.33)]
result = [list(t) for t in l]
print result

Output:

[['AAAA', 1.1100000000000001],
 ['BBB', 2.2200000000000002],
 ['CCCC', 3.3300000000000001]]
cletus
  • 616,129
  • 168
  • 910
  • 942
  • why do I get: TypeError: 'tuple' object is not callable? – DGT Jul 18 '10 at 02:43
  • @DGT no idea. what version of python are you using? The above is fine in 2.6/2.7. – cletus Jul 18 '10 at 02:56
  • 1
    @DGT: You're probably omitting a comma following a tuple. Something like (a, b, c) (d, e, f) will produce that error. The fixed version would be (a, b, c), (d, e, f) – Dan Breslau Jul 18 '10 at 03:39
1

You will need to unpack the tuple to append its individual elements. Like this:

l = [('AAAA', 1.11), ('BBB', 2.22), ('CCCC', 3.33)]

for each_tuple in l:
  result = ['something']
  for each_item in each_tuple:
    result.append(each_item)
    print result

You will get this:

['something', 'AAAA', 1.1100000000000001]
['something', 'BBB', 2.2200000000000002]
['something', 'CCCC', 3.3300000000000001]

You will need to do some processing on the numerical values so that they display correctly, but that would be another question.

Kit
  • 30,365
  • 39
  • 105
  • 149
  • No, not this. But this is the only guy who at least managed to read the question till the end. – Slava Jan 02 '17 at 16:47