2

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!

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76

4 Answers4

3
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.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
2

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

Community
  • 1
  • 1
b.b3rn4rd
  • 8,494
  • 2
  • 45
  • 57
  • tips: (1) don't name variables the same as built-ins (`list` is a built-in function), (2) use list comprehensions instead of `map` where possible because list comprehensions are faster and more readable. – nneonneo Jun 11 '14 at 03:35
0
list = []
num = 0
while (num != -1):
   num = input("Enter number; enter -1 to end: ")
   if (num != -1):
      list.append(num+1)
Shoikana
  • 595
  • 4
  • 8
  • This describes how to make a list from user input, but not how to increment the odd numbers. – nneonneo Jun 11 '14 at 03:35
  • That's true.. doesn't the original question state that the user inputs the information? – Shoikana Jun 11 '14 at 03:37
  • It's not clear _how_ the user inputs the information. Lacking that, it's hard to recommend a particular approach. (Your code is reasonable but not too Pythonic; I would recommend just using an infinite loop and a `break`, and losing the parentheses around the `while` and `if` conditions). – nneonneo Jun 11 '14 at 03:40
0

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
>>> 
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76