0

My (derailed) mind would like to do the following:

list1 = [1,2,3]
list2 = ['a','b','c']
list3 = [list([a for a in list2]).append(n) for n in list1]

to output this:

[['a', 'b', 'c', '1'], ['a', 'b', 'c', '2'], ['a', 'b', 'c', '3']]

only using single line list comprehensions (yes I'm in blinded by Haskell love).

Instead it outputs a list of 3 None type items which is understandable as I'm getting the output of append 3 times.

I think there's a key python idea I'm missing here on how I could make this work (or me being completely illogical), any help would be appreciated :)

1 Answer 1

4

No need to over-complicate things.

>>> list1 = [1,2,3]
>>> list2 = ['a','b','c']
>>> [list2 + [x] for x in list1]
[['a', 'b', 'c', 1], ['a', 'b', 'c', 2], ['a', 'b', 'c', 3]]
Sign up to request clarification or add additional context in comments.

12 Comments

Also can do: [[*list2, x] for x in list1]
If you did that, the result would be [['a','b','c',1],['a','b','c',1,2],['a','b','c',1,2,3]]
@Aris list3 = [(a := list([a for a in list2])).append(n) or a for n in list1] works (but it's bad)
@Aris Ha, just realized you even make a copy of a copy. Making double sure, eh?
@Aris Only you know why. You first copy with a list comprehension, then with the list call.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.