The question is Write a function called double_it() should iterate through the list and multiply each numeric element in the original list by 2 and reuturn integer representing the number of elements that were doubled.
Here is what I have..... the output is just repeating the list 2 times but not multiplying the values.
def main():
original_list = [input("Enter a list of numbers: ")]
double_it(original_list)
def double_it(new_list):
for index in range(len(new_list)):
new_list[index] *= 2
print new_list
main()
Your problem looks like an error with handling the input. The raw_input function should generally be preferred over input.
I'll defer to this Stack Overflow question: https://stackoverflow.com/questions/4663306/how-can-i-get-a-list-as-input-from-the-user-in-python
As for the doubling part, there are a few ways to do this that might be worth knowing about, to fully explore python.
>>> originalList = [1, 2, 3, 4, 5]
>>> newList = []
>>> for item in originalList:
... newList.append(item*2)
...
>>> print(newList)
[2, 4, 6, 8, 10]
>>> originalList = [1, 2, 3, 4, 5]
>>> newList = [item*2 for item in originalList]
>>> print(newList)
[2, 4, 6, 8, 10]
>>> def double(x): return 2*x
...
>>> originalList = [1, 2, 3, 4, 5]
>>> newList = list(map(double, originalList))
>>> print(newList)
[2, 4, 6, 8, 10]
The python docs around this stuff are all quite good, and an excellent learning resource.
Your double_it()
method works fine, just modify this line
original_list = [input("Enter a list of numbers: ")]
to
original_list = input("Enter a list of numbers: ")
Why? Because input()
will evaluate the list you enter as a list
, so you can work with it as a list, try printint the type :
a = input("Enter a list of numbers: ")
print type(a)
Enter a list of numbers: [1,2,3]
<type 'list'>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.