-1

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?

Chris
  • 132
  • 2
  • 10

3 Answers3

4

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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • https://stackoverflow.com/questions/16641119/why-does-append-always-return-none-in-python is another example of this issue, for OP to read – Ryan Rapini Oct 28 '19 at 21:00
0

First, it shouldn't be post_list.

>>> [[post]+list_b for post in list_a]
[['abc', 1, 2], ['def', 1, 2], ['opq', 1, 2]]
Bill Chen
  • 1,699
  • 14
  • 24
-1
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.

alex067
  • 3,159
  • 1
  • 11
  • 17
  • 1
    This is true, but not why OP gets the behavior he is describing. – Ryan Rapini Oct 28 '19 at 20:59
  • So my answer gets downvoted, because a miscalled / misplaced variable is less of an issue, than the return type of extend? Stackoverflow is just wonderful. – alex067 Oct 28 '19 at 21:04
  • how can you know that post_list isnt defined in the OP code. If it wasnt deifned he would get `NameError` but he doesnt mention that just says he gets list of `None` – Chris Doyle Oct 28 '19 at 21:19
  • If the OP does not provide the correct variable, how can we assume that the output provide is correct? – alex067 Oct 28 '19 at 21:20
  • Cause if it wasnt a defined variable he would get a `NameError` but thats not his compaint – Chris Doyle Oct 28 '19 at 21:28