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]
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]
A one line solution can be:
print [(i,'odd')[i%2] for i in list]
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)
for i in range(len (list)):
if (list[i] % 2 != 0):
list[i] = "odd"
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?
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"