-1

I have list a with below elements :

[[('433318', 0.7064461851335214), ('433363', 0.6709502341952089)],
 [('433395', 0.6988424611161282), ('433400', 0.6794787567547861)],
 [('433395', 0.6871546406771576), ('433363', 0.653218445986381)]]

Now I wanted retrieve the elements into a new list b which will have

['433318','433363','433395','433400','433395','433363']

a[0][0][0] gives ‘433318’
a[0][1][0] gives ‘433363’

But I am looking for a generic way (may be in a loop which iterates through the entire list) and gives me the desired result ?

1

2 Answers 2

3

Use a list comprehension:

l = [[('433318', 0.7064461851335214), ('433363', 0.6709502341952089)],
[('433395', 0.6988424611161282), ('433400', 0.6794787567547861)],
[('433395', 0.6871546406771576), ('433363', 0.653218445986381)]]

[y[0] for x in l for y in x]
Sign up to request clarification or add additional context in comments.

Comments

2

Using a list comprehension is best, but it may be helpful to see how a regular loop version would look like:

my_list = [[('433318', 0.7064461851335214), ('433363', 0.6709502341952089)],
[('433395', 0.6988424611161282), ('433400', 0.6794787567547861)],
[('433395', 0.6871546406771576), ('433363', 0.653218445986381)]]

result = []
for inner_list in my_list:
    for inner_tuple in inner_list:
        result.append(inner_tuple[0])

1 Comment

Thanks Federico to this loop explanation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.