Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 13891

How can I split a list of integers into odd and even numbers in Python? [closed]

$
0
0

I have a list of integers, for example:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I want to divide this list into two separate lists, one containing odd numbers and the other containing even numbers. How can I achieve this? Should I use a for loop, or is there another approach?

I attempted to use a for loop to iterate through the list and separate odd and even numbers into two distinct lists. My code looked like this:

odd_numbers = []even_numbers = []for num in numbers:    if num % 2 == 0:        even_numbers.append(num)    else:        odd_numbers.append(num)

I expected that after running this code, the odd_numbers list would contain all odd integers from the original list, and the even_numbers list would contain all even integers. However, I encountered an issue, and the separation did not work as expected.


Viewing all articles
Browse latest Browse all 13891

Trending Articles