TahaAvadi
TahaAvadi

Reputation: 11

Split list into two lists, odd and even, using a lambda

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?

Upvotes: 0

Views: 711

Answers (2)

Victor Bueno
Victor Bueno

Reputation: 29

You can use list comprehension

This is a more concise and efficient way to create filtered lists in Python. Here, listOne would be your original list, and you're creating listTwo containing the even numbers and listThree containing the odd numbers. This approach is considered more "pythonic" and is generally preferred for its readability and conciseness.

listTwo = [num for num in listOne if num % 2 == 0]
listThree = [num for num in listOne if num % 2 != 0]

The basic syntax of a list comprehension is:

new_list = [expression for item in iterable if condition]

Where:

  • expression is the expression you want to evaluate or manipulate for each item in the iterable.
  • item is a variable representing each element in the iterable.
  • iterable is the existing iterable (e.g., a list, tuple, or string) you want to iterate over.
  • condition is an optional filter that determines whether the item should be included in the new list.

For example, let's say you have a list of numbers and you want to create a new list containing only the squares of those numbers:

numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]

In this example:

  • num represents each number in the numbers list.
  • num ** 2 is the expression that calculates the square of each number.
  • There is no condition, so all numbers from the original list are included.

Upvotes: 2

JNevill
JNevill

Reputation: 50034

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)

Upvotes: 2

Related Questions