Mainland
Mainland

Reputation: 4564

Python extract elements from list of tuple

I am trying to extract elements from a list of tuples. I got the answer but wanted to know is there a better way? code:

pred_result_tuple  = [('n02123045', 'tabby', 0.5681726)]
pred_result_list = [x[n] for x in pred_result_tuple for n in [0,1,2]]

print(pred_result_list)
['n02123045', 'tabby', 0.5681726]

Tried but failed:

print([x[n] for x,n in zip(pred_result_tuple,[0,1,2])])
['n02123045']

Upvotes: 0

Views: 134

Answers (2)

BhusalC_Bipin
BhusalC_Bipin

Reputation: 811

import itertools
result = list(itertools.chain(*pred_result_tuple))

>>> print(result)
>>> ['n02123045', 'tabby', 0.5681726]

But, if you have only one tuple inside the list, you can do:

result = list(*pred_result_tuple)

>>> print(result)
>>> ['n02123045', 'tabby', 0.5681726]

Upvotes: 2

Supergamer
Supergamer

Reputation: 423

Use

Listoftuples=[(#elements)]
l=[]
for e in Listoftuples[0]:
    l=l+[e]
print(l)

Result

[#elements]

Upvotes: 1

Related Questions