jsj
jsj

Reputation: 9391

Python: What is zip doing in this list comprehension

I am trying to understand this:

a = "hello"
b = "world"
[chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)]

I understand the XOR part but I don't get what zip is doing.

Upvotes: 0

Views: 2124

Answers (2)

Tim
Tim

Reputation: 12174

zip combines each letter of a and b together.

a = "hello"
b = "world"
print zip(a, b)
>>>
    [('h', 'w'), ('e', 'o'), ('l', 'r'), ('l', 'l'), ('o', 'd')]

Upvotes: 3

sberry
sberry

Reputation: 132018

It isn't doing anything out of the ordinary for zip.

The list slicing of a is overkill since zip assumes this behavior.

As stated in the docs:

This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.

Upvotes: 2

Related Questions