0

I found an interesting function in Julia called zip. zip orders the calls to its subiterators in such a way that stateful iterators will not advance when another iterator finishes in the current iteration.
I would like to create a similar kind of code that gives output similar to Julia's zip.

For example, say a=1:5 and b=["e","d","b","c","a"], I would like to have an output where each value of both datasets is selected like this: (1,"e"),(2,"d"), (3,"b") and so on.

Is there any possible way to do this in Python?

2
  • 6
    there is the zip function in python that does exactly what you ask. zip(range(1,6), ["e","d","b","c","a"]) Commented Aug 13, 2020 at 12:06
  • If you find an answer that responds to your question, please accept it Commented Aug 14, 2020 at 7:01

1 Answer 1

1

This is done by the zip() function in Pyhton.

Here is some documentation about it. The description says :

Returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.
The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments which are all of the same length, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n).

And here are a few examples :

zip('foo', 'bar')
>>> [('f', 'b'), ('o', 'a'), ('o', 'r')]

zip((1, 1), (2, 4))
>>> [(1, 2), (1, 4)]

zip((1, 2, 3), (4, 5))
>>> [(1, 4), (2, 5)]

zip(range(1,6), ['a','b','c','f','k'])
>>> [(1,'a'), (2,'b'), (3,'c'), (4,'f'), (5,'k')]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.