Split list into two lists, odd and even, using a lambda
Question:
This is what I have:
ev_filt = filter(lambda x: x % 2 == 0, list1)
od_filt = filter(lambda x: x % 2 != 0, list1)
ev_list = list(ev_filt)
od_list = list(od_filt)
length = int(input("Enter the number of words yer gon pass"))
# initialize the list using for loop
for i in range(0, length):
item = int(input("Pass a number bro" + str(i+1) + " :"))
list1.append(item)
print(ev_list)
print(od_list)
I’ve tried to continue with this template, but it won’t work.
Why?
How do I solve this?
Answers:
Use list comprehension:
listTwo = [num for num in listOne if num % 2 == 0]
listThree = [num for num in listOne if num % 2 != 0]
As I mentioned in my comment, code runs from top to bottom in order. You sort your list1
into odd and even before it’s initialized and before there are values in the list. Switch the order and you should be golden:
length = int(input("Enter the number of words yer gon pass"))
# initialize the list using for loop
list1=[]
for i in range(0, length):
item = int(input("Pass a number bro" + str(i+1) + " :"))
list1.append(item)
ev_filt = filter(lambda x: x % 2 == 0, list1)
od_filt = filter(lambda x: x % 2 != 0, list1)
ev_list = list(ev_filt)
od_list = list(od_filt)
print(ev_list)
print(od_list)
This is what I have:
ev_filt = filter(lambda x: x % 2 == 0, list1)
od_filt = filter(lambda x: x % 2 != 0, list1)
ev_list = list(ev_filt)
od_list = list(od_filt)
length = int(input("Enter the number of words yer gon pass"))
# initialize the list using for loop
for i in range(0, length):
item = int(input("Pass a number bro" + str(i+1) + " :"))
list1.append(item)
print(ev_list)
print(od_list)
I’ve tried to continue with this template, but it won’t work.
Why?
How do I solve this?
Use list comprehension:
listTwo = [num for num in listOne if num % 2 == 0]
listThree = [num for num in listOne if num % 2 != 0]
As I mentioned in my comment, code runs from top to bottom in order. You sort your list1
into odd and even before it’s initialized and before there are values in the list. Switch the order and you should be golden:
length = int(input("Enter the number of words yer gon pass"))
# initialize the list using for loop
list1=[]
for i in range(0, length):
item = int(input("Pass a number bro" + str(i+1) + " :"))
list1.append(item)
ev_filt = filter(lambda x: x % 2 == 0, list1)
od_filt = filter(lambda x: x % 2 != 0, list1)
ev_list = list(ev_filt)
od_list = list(od_filt)
print(ev_list)
print(od_list)