Home > Mobile >  List comprehension not giving expected result
List comprehension not giving expected result

Time:02-05

I have a list of tuples, with each tuple containing a tuple pair, coordinates.

list1 = [((11, 11), (12, 12)), ((21, 21), (22, 22)), ((31, 31), (32, 32))]

Using list comprehension I am trying to generate a list without them being paired but still in the same order. I was able to get the result be looping and using .append() but I was trying to avoid this.

new_list = []
for i in list1:
    for x in i:
        new_list.append(x)

print(new_list)

this works and gives me the result I am looking for:

[(11, 11), (12, 12), (21, 21), (22, 22), (31, 31), (32, 32)]

But when I try list comprehension I get the last tuple pair repeated!

new_list = [x for x in i for i in list1]
print(new_list)
[(31, 31), (31, 31), (31, 31), (32, 32), (32, 32), (32, 32)]

I am sure it is a small thing I am doing wrong so would appreciate the help!!

CodePudding user response:

try :

print([inner_tuple for outer_tuple in list1 for inner_tuple in outer_tuple])

Nested fors should come to the right side. for sub in list1 after that for x in sub.

And btw, you didn't get NameError: name 'i' is not defined because, you wrote that list-comprehension after the for loop. In that time i is a global variable and exists.

CodePudding user response:

The execution of the loop is out-inner type Your code misses is close but it takes x only

  • Your code:
new_list = []
for i in list1:
    for x in i:
        new_list.append(x)

  • which is equivalent to
new_list = [x for i in list1 for x in i]

So, now you can understand the variables how they are taking values from for loops

  •  Tags:  
  • Related