Home > Enterprise >  Iterate through second values in list of tuples
Iterate through second values in list of tuples

Time:10-13

I have a list of tuples [(0, 1), (0, 3), (4, 3)] and I want a for loop that lets me work with the second value of each tuple. In this example I want the loop variable to have the values 1, 3, 3. Is there a simple way to do this or do I have to use this:

for tuple in list:
    ... = tuple[1]

To clarify, I'm looking for something like:

for item in list:  # item is the second item in each tuple
    ...

CodePudding user response:

a = [(1, 2), (3, 4)]

for _, y in a:
    print(y)

If you want something more general and elegant, you can write your own generator function that yields the n-th element from each sequence in a specified iterable of sequences:

from collections.abc import Iterable, Iterator, Sequence
from typing import TypeVar


T = TypeVar("T")


def nth(n: int, it: Iterable[Sequence[T]]) -> Iterator[T]:
    for tup in it:
        yield tup[n]


if __name__ == '__main__':
    a = [(1, 2), (3, 4)]
    for item in nth(1, a):
        print(item)

Both give the output:

2
4

EDIT: Added proper type annotations.

  • Related