I realized that return breaks in a function thus I need to find an alternate way to return a modified list.
def multiply(lst):
new = ''
for i in range(len(lst)):
var = lst[i] * 3
new = new + str(var)
return new
list1 = [1,2,3]
received = multiply(list1)
print [received]
I’m trying to multiply all elements by 3 and return (I have to use return). This just gives returns
[‘369’]
The list I’m trying to return is
[3,6,9]
That’s because
newisn’t a list. In the first line ofmultiply(), you donew = ''. This means thatnewis a string.For strings, the addition operator,
+, performs concatenation. That is to say:and similarly:
or
Clearly, this is not what you want. In order to do what you want, you should construct a new list and return it:
Of course, accessing the list elements by index is not very “pythonic”. The rule of thumb is: “unless you need to know the indices of the list elements (which you don’t, in this case), iterate over the values of the list”. We can modify the above function accordingly:
Finally, python has something called a list comprehension, which does the same thing as above, but in a much more concise (and faster) way. This is the preferred method:
For more on list comprehensions, see the following tutorial: http://www.blog.pythonlibrary.org/2012/07/28/python-201-list-comprehensions/