-2

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.

xiver77
  • 1,299
  • 1
  • 1
  • 11

2 Answers2

0

.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]
>>>
BrokenBenchmark
  • 13,997
  • 5
  • 12
  • 27
0

This is not how append works. Read this documentation to understand more . On quick note append adds item to end of a list.

Now, regarding your question you should make new variable storing l[0] and then append the remaining value to it. The code should look like this.

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