I have a list1 = [3,4,5,6,7,8]
. I want append to a list2
such that Add 10
to even number
and multiply with 5
if it is an odd number in the list1
with Python.
I've tried this
list1 = [3, 4, 5, 6, 7, 8]
list2 = []
for num in list1:
if (num%2) == 0:
num + 10
list2.append(num)
else:
num*5
list2.append(num)
list2
got it...
import numpy as np
list1 = [3, 4, 5, 6, 7, 8]
list2 = []
for num in list1:
if (num%2) == 0:
x = num + 10
list2.append(x)
else:
x = num*5
list2.append(x)
list2
You are not storing num+10
or num*5
anywhere. Try this -
list1 = [3, 4, 5, 6, 7, 8]
list2 = []
for num in list1:
if (num%2) == 0:
list2.append(num + 10) #<----
else:
list2.append(num*5) #<----
list2
[15, 14, 25, 16, 35, 18]
You can also try using list comprehension which is a one liner that does the same thing as above -
list2 = [num+10 if (num%2)==0 else num*5 for num in list1]
[15, 14, 25, 16, 35, 18]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.