Reputation: 169
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]
Upvotes: 1
Views: 504
Reputation: 24788
That's because new
isn't a list. In the first line of multiply()
, you do new = ''
. This means that new
is a string.
For strings, the addition operator, +
, performs concatenation. That is to say:
'a' + 'b' => 'ab'
and similarly:
'1' + '2' => '12'
or
new = ''
new + str(var) => '' + '3' => '3'
Clearly, this is not what you want. In order to do what you want, you should construct a new list and return it:
def multiplyBy3(lst):
newList = [] #create an empty list
for i in range(len(lst)):
newList.append(lst[i] * 3)
return newList
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:
def multiplyBy3(lst):
newList = []
for item in lst: #iterate over the elements of the list
newList.append(item * 3)
return newList
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:
def multiplyBy3(lst):
return [item * 3 for item in lst] #construct a new list of item * 3.
For more on list comprehensions, see the following tutorial: http://www.blog.pythonlibrary.org/2012/07/28/python-201-list-comprehensions/
Upvotes: 3
Reputation: 29103
Try this:
def multiply(lst):
return [val*3 for val in lst]
list1 = [1,2,3]
received = multiply(list1)
print received
In case you want in-place editing you can to the following:
def multiply(lst):
for idx,val in enumerate(lst):
lst[idx] = val*3
return lst
The problem in your code that you are merging strings '3', '6' and '9' and return one variable that contains string('369') Than you putting this string in list. That is why you have ['369'] instead of [3,6,9].Please find your code with comments below:
def multiply(lst):
new = '' # new string
for i in range(len(lst)): # for index in range of list size
var = lst[i] * 3 # get value from list and mupltiply by 3 and then assign to varible
new = new + str(var) # append to string new string representation of value calculated in previous row
return new #return string
In any case is a good way to debug your code by putting prints with variable used - though that if you place prints in your code you will understand what is going there
Upvotes: 4
Reputation: 52253
>>> multiply = lambda l: map(lambda x: x*3, l)
>>> multiply([1,2,3])
[3, 6, 9]
Upvotes: 0