Nested list comprehension with two lists

后端 未结 5 906
误落风尘
误落风尘 2020-12-08 06:09

I understand how the simple list comprehension works eg.:

[x*2 for x in range(5)] # returns [0,2,4,6,8]

and also I understand how the nested

5条回答
  •  被撕碎了的回忆
    2020-12-08 06:51

    [x + y for x in l2 for y in l1 ]
    

    is equivalent to :

    lis = []
    for x in l:
       for y in l1:
          lis.append(x+y)
    

    So for every element of l you're iterating l2 again and again, as l has 3 elements and l1 has elements so total loops equal 9(len(l)*len(l1)).

提交回复
热议问题