Search code examples
pythoniteratortuplespython-itertoolscycle

Itertool Cycle function to access the first value only once in tuple


I want to add the first value in a tuple to a list which is something like this t=((1,2,3,4), (5,6,7,8))

I want to use cycle function (some question) to access the first value of tuple i.e. t[0] to store in a list i.e equivalent to this:

list1=[]
list1.append(t[0])

How can I use cycle (if one has to) to cycle through the tuple t to store the first indexed value in list1?


Solution

  • Slurp all elements from an iterable

    You can use extend:

    t=((1,2,3,4), (5,6,7,8))
    lst = []
    
    lst.extend(t[0])  # takes an iterable
    print(lst)
    

    Output:

    [1, 2, 3, 4]
    

    Append an element from every indexed tuple

    If you wanted to append only the first index of every entry in the tuple t:

    t=((1,2,3,4), (5,6,7,8))
    lst = [_t[0] for _t in t]
    print(lst)
    

    Output:

    [1, 5]