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.
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.
[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.
If you break down the phrase ((1,2),(3,4))
you end up with a tuple
of two tuple
s.
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)
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
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
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']
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))]