Skip to content
Advertisement

Assign a subset of values from a list returned by an iterable to a variable (Python)

I have an iterable that returns multiple values as a list. In this case, I only care about one of the values in each iteration.

As a concrete example:

JavaScript

This produces:

JavaScript

But I really just want:

JavaScript

I could just do:

JavaScript

or:

JavaScript

or:

JavaScript

but it feels like it would be nicer to tell Python that I’m uninterested in all the other values instead of storing them in a place I won’t look. (And adding a del(_) feels both too late and too aggressive.)

In particular, this doesn’t work:

JavaScript

(It errors out with TypeError: 'Triples' object is not subscriptable; note that that makes this related question‘s highest-rated answer incorrect for this case.)

and this:

JavaScript

Does the wrong thing. It generates the whole list of lists and then returns the second list (instead of the second element of each list), and produces:

JavaScript

Is there something better or should I just do one of the things I already mentioned?

Advertisement

Answer

The solutions you already have are likely the clearest ones available.

I’d go for either indexing:

JavaScript

Or unpacking with dummy names:

JavaScript

But if neither of those are satisfying to you, there are a few more options. If you really needed to get a list or iterator of just the second values from the iterator, you could write a list comprehension or generator expression, separate from the loop:

JavaScript

For a finite iterator, you could also play around with zip(*Triples()), to transpose your data so you can index it all at once to get the second values from every result:

JavaScript

That is not be very easily understandable though, and consumes the entire iterator up-front, rather than lazily as the iteration happens.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement