Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Appending an element in nested list comprehension python

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’]]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 🙂

>Solution :

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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading