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

append to a list doesn't work as expected

Sorry for a dumb and simple question, but I don’t understand why the following Python code doesn’t work as expected.

>>> l = [1, '+', 2, '']
>>> l
[1, '+', 2, '']
>>> [l[0]]
[1]
>>> l[2:]
[2, '']
>>> l[2:][0]
2
>>> [l[0]].append(l[2:][0])
>>>

I was expecting [1, 2], but the expression is evaluated to nothing.

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

>Solution :

.append() returns None, so no output occurs. Create a new variable, e.g. result that holds [l[0]], and then append to that list. Then, output that variable result on the REPL, and it should give the desired output.

For example:

>>> l = [1, '+', 2, '']
>>> l
[1, '+', 2, '']
>>> result = [l[0]]
>>> result.append(l[2:][0])
>>> result
[1, 2]
>>>
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