Python: How to combine the results of for loop into one output?
11,408
Solution 1
Use a list comprehension:
[num*2 for num in numbers]
>>> numbers = [1, 2, 3]
>>> [num*2 for num in numbers]
[2, 4, 6]
>>>
Solution 2
Create new List type variable result
and add values into it by list append()
method.
Demo:
>>> numbers = [1, 2, 3]
>>> result = []
>>> for i in numbers:
... result.append(i*2)
...
>>> result
[2, 4, 6]
>>>
Author by
juiceb0xxie
Updated on June 27, 2022Comments
-
juiceb0xxie almost 2 years
numbers = [1, 2, 3] for number in numbers: number = number * 2 #For the output I will get: 2 4 6
How do I modify my code so the results can be combined (eg. [2, 4, 6]) without using the print statement?
-
wallyk about 9 yearsDo you mean you do not want to output the result? Only calculate it?
-
abarnert about 9 yearsI don't know what you mean "# For the output I will get: 2 4 6". There is no output here at all. And no effect; all you're doing each time through the loop is reassigning the loop variable
number
to a different value, which you then immediately forget. -
TigerhawkT3 about 9 yearsIt sounds like you're confusing the Python interpreter's behavior of displaying
return
ed values with the built-inprint()
function.
-