Reputation: 33
I'm puzzled. I've executed zip on two sets of lists and get different results. I'm hoping a seasoned expert can help me understand where my thinking has gone wrong.
s1 and s2 represent two phrases which will always be one to three words long. I need to stack the words of the phrases into columns (with the stack bottom-justified). I don't understand why the two calls to zip return different results. I've used repr and both function parameters appear identical.
>>> s1 = 'a b'
>>> s2 = 'c d'
>>> s1.split(' '),s2.split(' ')
(['a', 'b'], ['c', 'd'])
>>> tokens = s1.split(' '),s2.split(' ')
>>> tokens
(['a', 'b'], ['c', 'd'])
>>> zip(s1.split(' '),s2.split(' '))
[('a', 'c'), ('b', 'd')]
>>> zip(tokens)
[(['a', 'b'],), (['c', 'd'],)]
Upvotes: 0
Views: 63
Reputation: 47988
The way returns are displaying in your interactive console is throwing you off a bit.
# This calls zip with 2 arguments.
>>> zip(s1.split(' '),s2.split(' '))
[('a', 'c'), ('b', 'd')]
# This calls zip with 1 argument.
>>> zip(tokens)
[(['a', 'b'],), (['c', 'd'],)]
# This unpacks the tuple and calls zip with 2 arguments again,
>>> zip(*tokens)
[('a', 'c'), ('b', 'd')]
Upvotes: 1
Reputation: 7552
you've got to read the parenthesis very carefully:
>>> tokens = s1.split(' '),s2.split(' ')
>>> tokens
(['a', 'b'], ['c', 'd'])
the return value was a single tuple consisting of two lists
so, you're passing a single element to zip
. if you address the elements separately, you get
>>> zip(tokens[0], tokens[1])
[('a', 'c'), ('b', 'd')]
>>> zip(*tokens)
[('a', 'c'), ('b', 'd')]
Upvotes: 0