Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

append tuples to a list

Tags:

python

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]
like image 613
DGT Avatar asked Jul 18 '10 02:07

DGT


4 Answers

result.extend(item)
like image 151
Ignacio Vazquez-Abrams Avatar answered Sep 27 '22 23:09

Ignacio Vazquez-Abrams


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])
like image 39
John Avatar answered Sep 27 '22 23:09

John


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]]
like image 45
cletus Avatar answered Sep 27 '22 23:09

cletus


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.

like image 35
Kit Avatar answered Sep 27 '22 23:09

Kit