For example: ([3,85,44,71,9,5])
would return ([4,86,44,72,10,6])
The user inputs the information, so would I have to create an empty list?
Lots of help would be appreciated
Thank you!
For example: ([3,85,44,71,9,5])
would return ([4,86,44,72,10,6])
The user inputs the information, so would I have to create an empty list?
Lots of help would be appreciated
Thank you!
list1 = [3,85,44,71,9,5]
list2 = [x + (x%2) for x in list1]
noting that x%2
is 1 for odd numbers and 0 for even numbers.
Using lambda and ternary operator:
list1 = [3,85,44,71,9,5]
map(lambda x: x if x%2==0 else x+1, list1)
[4, 86, 44, 72, 10, 6]
P.S. Related discussion: Python List Comprehension Vs. Map
list = []
num = 0
while (num != -1):
num = input("Enter number; enter -1 to end: ")
if (num != -1):
list.append(num+1)
Use modulo
:
arr = [3,85,44,71,9,5]
arr = [item + item%2 for item in arr]
This runs as:
>>> arr = [3,85,44,71,9,5]
>>> arr = [item + item%2 for item in arr]
>>> arr
[4, 86, 44, 72, 10, 6]
>>>
%
works as such:
>>> 9%2 #Gives 1, because 9/2 is 4 remainder 1
1
>>> 10%2 #Gives 0, because 10/2 is 5 remainder 0
0
>>>