2

can you explain this code

[y for _, y in ((1,2),(3,4))]

output is [2, 4]

I do not find a document to use this syntax, but it can be run.

DeGo
  • 783
  • 6
  • 14
Yao Yuan
  • 350
  • 3
  • 11
  • The source list contains 2-element tuples so we need to assign two variables to the output, for example we can have `x, y` or `foo, bar` but in this case we don't care about the first one so we assign it to a throwaway variable name `_` – NotAName Apr 15 '21 at 06:49
  • What is the question? – Hans Lub Apr 15 '21 at 06:50

6 Answers6

2

[y for _, y in ((1,2),(3,4))] is a List Comprehension.

This is equivalent to below for:

In [2935]: l = []

In [2936]: for _, y in ((1,2),(3,4)):
      ...:     l.append(y)
      ...: 
      ...: 

In [2937]: l
Out[2937]: [2, 4]

Also _ is a throw-away variable, which means variables you are using while iterating but not really using them for any other purposes.

Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
2

If you break down the phrase ((1,2),(3,4)) you end up with a tuple of two tuples.

So the iteration goes over the outer tuple, taking the first item in _ and the second in y, from which you take only the second variable, y, and create a new list.

This is as same as this code, which is easier to grasp first:

my_set = ((1,2), (3,4))
my_list = []
for _, y in myset:
    my_list.append(y)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Chen A.
  • 10,140
  • 3
  • 42
  • 61
1

If I convert code to

[y for             x,y in ((1,2),(3,4))]

it is easy to understand _ is equal x

, is in the second statement

Yao Yuan
  • 350
  • 3
  • 11
0

You can effectively expand the code as

t = ((1,2),(3,4))
print([y for x, y in t])

Here, replacing x with _ gives back the original one-liner

DeGo
  • 783
  • 6
  • 14
0
print([item for item in (("id", 1), ("name", "Yao Yuan"))])
# Output: [('id', 1), ('name', 'Yao Yuan')]
print([(item[0], item[1]) for item in (("id", 1), ("name", "Yao Yuan"))])
# Output: [('id', 1), ('name', 'Yao Yuan')]
print([(key, value) for key, value in (("id", 1), ("name", "Yao Yuan"))])
# Output: [('id', 1), ('name', 'Yao Yuan')]
print([key for key, value in (("id", 1), ("name", "Yao Yuan"))])
# Output: ['id', 'name']
print([value for key, value in (("id", 1), ("name", "Yao Yuan"))])
# Output: [1, 'Yao Yuan']
BaiJiFeiLong
  • 3,716
  • 1
  • 30
  • 28
0

the syntax with comma x1, x2, ...., xn = (y1, y2, ...., yn) is used to unpack an iterable of length n into n individual variables. The undescore used during unpacking iterables is to say that you don't care about the value in a certain index of the iterable you are unpacking.

so basically, your example is using a list comprehension in which you first unpack each index in the iterable ((1,2),(3,4)) into variables _, y (where _ means disregarding index 0), then you comprehend all y variables into a list = [2, 4]

[y for _, y in ((1,2),(3,4))]
tbjorch
  • 1,544
  • 1
  • 8
  • 21