Why does list comprehension using a zip object results in an empty list?
-
21-08-2019 - |
Question
f = lambda x : 2*x
g = lambda x : x ** 2
h = lambda x : x ** x
funcTriple = ( f, g, h )
myZip = ( zip ( funcTriple, (1, 3, 5) ) )
k = lambda pair : pair[0](pair[1])
# Why do Output # 1 (2, 9, 3125) and Output # 2 ( [ ] ) differ?
print ("\n\nOutput # 1: for pair in myZip: k(pair) ...")
for pair in myZip :
print ( k(pair) )
print ("\n\nOutput # 2: [ k(pair) for pair in myZip ] ...")
print ( [ k(pair) for pair in myZip ] )
# script output is ...
# Output # 1: for pair in myZip: k(pair) ...
# 2
# 9
# 3125
#
# Output # 2: [ k(pair) for pair in myZip ] ...
# []
Solution
Works perfectly in Python 2.6 but fails in Python 3.0 because zip
returns a generator-style object and the first loop exhausts it. Make a list instead:
myZip = list( zip ( funcTriple, (1, 3, 5) ) )
and it works in Python 3.0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow