简体   繁体   中英

Why this list comprehension doesn't work?

I am trying to create a new embeded list from two lists(a and b) as below:

list_a = ['abc','def','opq']
list_b = [1,2]
resulting_list = 
[['abc',1,2],
 ['def',1,2],
 ['opq',1,2]]

I have tried below below function with list comprehension, but it doesn't return expected result.

def combine_list(list_a, list_b):
    return [[post].extend(list_b) for post in list_a]

I expected to return:

[['abc',1,2],
 ['def',1,2],
 ['opq',1,2]]

instead, I got

[None, None, None]

Why doesn't the list comprehension work?

extend is a mutator. It modifies the list on the left and returns nothing. List comprehensions should stick to functional, side-effect-free operations.

[[post] + list_b for post in list_b]

And change post_list to list_b .

First, it shouldn't be post_list.

>>> [[post]+list_b for post in list_a]
[['abc', 1, 2], ['def', 1, 2], ['opq', 1, 2]]
def combine_list(list_a, list_b):
return [[post].extend(list_b) for post in post_list]

Because post_list doesn't exist anywhere in your function, or as a global variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM