I'm trying to figure out why my nested list comprehension doesn't work. Code:
def myzip(*args):
try:
x = [iter(i) for i in [*args]]
while True:
# for i in range(5):
yield [next(ii) for ii in x]
# I want to know why the commented line below won't work
# yield [next(ii) for ii in [iter(i) for i in [*args]]]
# or why this outputs [1, 'a']
# return [next(ii) for ii in [iter(i) for i in [*args]]]
except:
pass
def main():
print(list(myzip([1, 2, 3, 4, 5], ['a', 'b', 'c'])))
if __name__ == '__main__':
main()
if I assign [iter(i) for i in [*args]] to x and then use this list comprehension [next(ii) for ii in x] everything works ok. and the output will be:
[[1, 'a'], [2, 'b'], [3, 'c']]
But if I try to ommit variable x and do it in one bigger list comprehension (commented line) [next(ii) for ii in [iter(i) for i in [*args]]] it goes in infinite loop. If you replace infinite loop with the for loop (commented line), the output is:
[[1, 'a'], [1, 'a'], [1, 'a'], [1, 'a'], [1, 'a']]
Moreover, if I try return [next(ii) for ii in [iter(i) for i in [*args]]] it just returns:
[1, 'a']
Can someone tell me why is that?