0

this is the code its just following questions i have received but i have been asked to append all even numbers from list1 into list2 how could i achieve this

import random

list1 = []
for x in range(10):
print(random.randint(1,101))
list1.append(x)
list2 = list1

print(list1)
print(list2)

i have checked all over google cant find a page that can help me i have tried :

num = list1
if (num % 2) == 0:
  print("{0} is Even".format(num))
else:
  print("{0} is Odd".format(num))

1 Answers1

0

There's no need to append, you can create list2 through a list comprehension:

list2 = [i for i in list1 if i%2==0]
# [0, 2, 4, 6, 8]

If you really want to use a loop with append, you can do:

# create empty list
list2 = []
# loop through and append if even:
for i in list1:
    if i%2 == 0:
        list2.append(i)
sacuL
  • 49,704
  • 8
  • 81
  • 106