1

For instance, how would I define a function so that every odd integer in a list is replaced with the string 'odd'? Thanks

list = [10 , 11, 12, 13, 14, 15, 16,]

Intended result

[10, 'odd', 12, 'odd', 14, 'odd', 16]
Gabriel A
  • 21
  • 2
  • 2
  • 4
  • 2
    Have you read about loops and conditionals?. – Reti43 Apr 05 '16 at 00:15
  • 2
    Note: Please do not name a variable the same as a Python built-in. In this case `list` then masks the built-in function `list(iterator)` – dawg Apr 05 '16 at 00:28

5 Answers5

2

A one line solution can be:

print [(i,'odd')[i%2] for i in list]
zondo
  • 19,901
  • 8
  • 44
  • 83
Kautsya Kanu
  • 451
  • 1
  • 7
  • 20
  • 1
    Reverse the tuple for more clarity: `[(x,'odd')[x%2] for x in list]` – dawg Apr 05 '16 at 00:26
  • It is also better to use a tuple `(x,'odd')` rather than a list `[x,'odd'] since the tuple is constructed once and the list each and every time through the loop... – dawg Apr 05 '16 at 00:30
1

I feel like you should probably get the solution on your own, but anyway...

result = []
for i in list:
    if i % 2 != 0:
        result.append('odd')
    else:
        result.append(i)

Or, maybe something to push you forward:

def turn_odd(i):
    if i % 2 != 0:
        return 'odd'
    else:
        return i

list = [10 , 11, 12, 13, 14, 15, 16,]
result = map(lambda x: turn_odd(x), list)
Water Crane
  • 43
  • 1
  • 9
0
for i in range(len (list)):
    if (list[i] % 2 != 0):
        list[i] = "odd"
Jeremy Hanlon
  • 317
  • 1
  • 3
0

You can use list comprehension:

list = [10 , 11, 12, 13, 14, 15, 16]
new_list = [i if i % 2 == 0 else "odd" for i in list]

Here's a good example of how it works: if/else in Python's list comprehension?

Community
  • 1
  • 1
Will
  • 4,299
  • 5
  • 32
  • 50
  • Technically this isn't what OP asked for. OP asked to replace the odd elements of a list, not generate a new list with the odd elements replaced. Whether this matters to OP or not is unclear, but it does create a new list. – Tom Karzes Apr 05 '16 at 00:29
  • 1
    You could do `list[:] = ...` instead of `new_list = ...` You shouldn't be using `list` as a variable name anyway because it shadows the built-in type. You could also do `["odd" if i % 2 else i for i in list]` – zondo Apr 05 '16 at 00:43
0

First note that list is reserved for the type list in Python, so I will use my_list instead. Then you have three options:

A loop with a conditional

for i in range(0, len(my_list)):
    if (i % 2 != 0):
        my_list[i] = "odd"

List comprehension (same logic as above)

my_list = ["odd" if i % 2 != 0 else my_list[i] for i in range(len(my_list))]

A loop without a conditional

for i in range(1, len(my_list), 2):
     my_list[i] = "odd"
T. Silver
  • 372
  • 1
  • 6