I have this list in python
[a,b,c,d,e,f,g,h]
How can I get the elements by pairs stored in a list of tuples. Thus:
[(a,b),(c,d),(e,f),(g,h)]
I have this list in python
[a,b,c,d,e,f,g,h]
How can I get the elements by pairs stored in a list of tuples. Thus:
[(a,b),(c,d),(e,f),(g,h)]
I was able to solve it using the zip function.
Generating a list made up of tuples using the zip function
Result for zipped:
A generic solution to get
N
item tuples from a list:Explanation in parts:
iter(lista)
get an iterator from the list[iter(lista)]*n
create a list of lengthn
using the same repeated iteratorzip(*[iter(lista)]*n)
passes the list as an argument, equivalent to passingn
the iterator times. That is, it iszip(*[it]*2)
equivalent tozip(it,it)
list(zip(*[iter(lista)]*n))
convert the result to a list (in python3, zip returns another iterator)