Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to split the even and odd elements into two different lists.
In this article, we are going to learn about splitting the even and odd elements into two different lists. This involves looping through each element in a list and checking whether it is divisible by 2. Even numbers are those that give the remainder '0' when divided by 2, while the odd numbers leave a remainder '1'.
Using append() Method
The Python append() method is used to add a new object to a list. It accepts an object as an argument and inserts it at the end of the existing list.
Syntax
list.append(obj)
In this approach, we initialize three lists: one contains the input numbers, and two empty lists to store even and odd numbers separately. We use a conditional expression to check whether each number is divisible by 2 ?
Example
numbers = [1, 22, 3, 44]
even_numbers = []
odd_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
else:
odd_numbers.append(num)
print("Even numbers:", even_numbers)
print("Odd numbers:", odd_numbers)
Even numbers: [22, 44] Odd numbers: [1, 3]
Using List Comprehension
Python list comprehension offers a concise way to create lists using a single line of code. It combines loops and conditional statements, making it more efficient than traditional methods ?
Syntax
newlist = [expression for item in iterable if condition == True]
In this approach, we use list comprehension to construct even and odd number lists in separate statements ?
Example
numbers = [11, 2, 33, 4, 55]
even_numbers = [num for num in numbers if num % 2 == 0]
odd_numbers = [num for num in numbers if num % 2 != 0]
print("Even numbers:", even_numbers)
print("Odd numbers:", odd_numbers)
Even numbers: [2, 4] Odd numbers: [11, 33, 55]
Using filter() Function
The filter() function creates an iterator from elements that pass a test function. This approach is functional programming style and memory-efficient for large datasets ?
numbers = [7, 14, 21, 28, 35]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
odd_numbers = list(filter(lambda x: x % 2 != 0, numbers))
print("Even numbers:", even_numbers)
print("Odd numbers:", odd_numbers)
Even numbers: [14, 28] Odd numbers: [7, 21, 35]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| append() with loop | High | Good | Beginners, complex logic |
| List comprehension | Medium | Best | Pythonic, concise code |
| filter() function | Medium | Good | Functional programming |
Conclusion
List comprehension is generally the most Pythonic and efficient approach for splitting even and odd numbers. Use the append() method for more complex logic or when learning Python fundamentals.
