Reputation: 33
Let's say I have a list of tuples:
myList = [(1,2,3) , (2,3,4) , (3,4,5) ,(4,5,6) , (1,3,5) , (2,4,6)]
I want to iterate over it, but just gonna use the first two indexes of each tuple.
So I'd be actually iterating over:
[(1,2) , (2,3), (3,4), (4,5), (1,3), (2,4)]
I know I can do this:
for item in myList
And then in my code just use item[0], item [1]
, but I think this will really affect the readbility of my code.
But I have this for
in a list comprehension so (I think) I can't store those values in other variable.
My question here is: Would using a dummy variable like:
for (variablename1,variablename2,dummyvar) in myList
be the best way to do that or there is a direct way to return only the first indexes from the for
?!
(I accept hints to better clarify the question ;) )
Upvotes: 0
Views: 40
Reputation: 73470
Using the anonymouos variable _
is typical in such cases:
for x, y, _ in myList:
# do stuff with x and y
If the tuples have various lengths, you can do:
for x, y, *_ in myList:
# do stuff with x and y
to avoid errors.
Upvotes: 3