Nikko
Nikko

Reputation: 1572

A way for iterable zip like single element for Python

Hi guys I just want to know if there's a way to iterate over a tuple that behaves like zip.

For example:

zipper = zip(['aye', 'bee'], ['ex', 'why'])
for x, y in zipper:
    print(x, y)
aye ex
bee why

tupl = 3, 2
for x, y in tupl:
    print(x, y)
# 'int' object is not iterable.

What I knew now is that it can't be zip-ed:

tupl = zip(3, 2)
# zip argument #1 must support iteration

I am trying to pass zipper into a function, I also hope to pass the tuple or a single set of zip.

def processthis(zipper):
    for x, y in zipper:
        # do something with x and y

Upvotes: 1

Views: 54

Answers (2)

imjp94
imjp94

Reputation: 96

Parenthesis are missing.

When passing a tuple to function, it needs to be wrapped by parenthesis.

In your case,

zip((3, 2), (4, 5))  # zipping 2 tuples

Otherwise, zip will sees 3 and 2 as two positional arguments.

Upvotes: 0

blhsing
blhsing

Reputation: 106598

With a loop of for x, y in tupl: you are expecting tupl to be a sequence of tuples, rather than a tuple.

If you want your loop to process only one tuple you should assign tupl with [(3, 2)] instead of (3, 2).

Upvotes: 3

Related Questions