0

I found this block of code in my homework file. But I cannot understand its output

arr = [[3,2,1], ['a','b','c'], [('do',), ['re'], 'mi']]
print([el.append(el[0] * 4) for el in arr])  # What is printed?
print(arr)

the result should be [None,None,None]

Rieder
  • 1,125
  • 1
  • 11
  • 18
  • Because `append` doesn't return a value? – Felix Kling Jan 25 '19 at 06:54
  • arr = [[3,2,1], ['a','b','c'], [('do',), ['re'], 'mi']] print([el.append(el[0] * 4) for el in arr]) this line will append, whatever in the 0 position of each list multiplied by 4 for example '12' for the first list,'aaaa' for the second. but the print command given in second line will print the result of the append command. Append command simple adds to the list and return nothing, that is why you are getting 'None' for each command execution. refer : https://www.programiz.com/python-programming/methods/list/append – BlindSniper Jan 25 '19 at 07:07
  • sadly the question is closed – BlindSniper Jan 25 '19 at 07:08

1 Answers1

0

append() is a list method that modifies the list in-place. So a.append("foo") changes a by adding the element "foo" at the end. These methods do not need to return anything, so they don't.

Therefore, if you build a list using a list comprehension that is constructed using the returned values of a series of append() method calls, you'll get a series of Nones.

If you don't want to modify the original list, you can do something like

>>> print([item + [item[0]*4] for item in arr])
[[3, 2, 1, 12], ['a', 'b', 'c', 'aaaa'], [('do',), ['re'], 'mi', ('do', 'do', 'do', 'do')]]

If you do want to modify the original list, you should do

>>> for item in arr:
...     item.append(item[0]*4)
...
>>> print(arr)
[[3, 2, 1, 12], ['a', 'b', 'c', 'aaaa'], [('do',), ['re'], 'mi', ('do', 'do', 'do', 'do')]]

But you shouldn't try doing both at the same time. Using side effects in list comprehensions is almost always a bad idea.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • 1
    Wouldn't it be more useful to just vote as duplicate, with your hammer? – iBug Jan 25 '19 at 07:01
  • 1
    The problem is if you want to print a list, you should be able to do that right? I do not get it why do i need to return something – Rieder Jan 25 '19 at 07:19