Please guide how to solve this
def double_list(numbers):
return 2 * numbers
numbers = [1, 2, 3]
print(double_list(numbers))
Please guide how to solve this
def double_list(numbers):
return 2 * numbers
numbers = [1, 2, 3]
print(double_list(numbers))
First, make sure you get the indentation right. Maybe you did, maybe you did not, but put your code into blocks using the </>
key:
def double_list(numbers):
return 2 * numbers
numbers = [1, 2, 3]
print(double_list(numbers))
If you run this, I get
[1, 2, 3, 1, 2, 3]
I am confused why it gives… [1, 2, 3, 1, 2, 3]
not [2, 4, 6]??
I’m not sure what the history of it is, but operator * just does this with lists. It does something similar if you use it with a string:
IPython 7.30.1 -- An enhanced Interactive Python. Type '?' for help.
In [1]: a = "a" * 3
In [2]: a
Out[2]: 'aaa'
operator *
doesn’t perform a matrix multiplication with lists. It specifies a number of repetitions of the list elements
With the string example provided by Rob, a string is treated as a list of characters, so similarly "abc" * 2
yields "abcabc"
The issue with your code is that it’s doubling the number of elements by repeating entire list, not doubling each individual element value in the list.
To achieve [2, 4, 6] the code should be like :
def double_list(numbers):
return list(map(lambda i: 2 * i, numbers))
numbers = [1, 2, 3]
print(double_list(numbers))
OR
def double_list(numbers):
return [2 * i for i in numbers]
numbers = [1, 2, 3]
print(double_list(numbers))
Hope, this helps!
Thanks.