Hello everyone! Welcome back to Programming In Python. Here in the post am going to add one more program which covers the Python data-type list
. Here I will separate all the even and odd numbers from a list into two different lists.
Master the basics of data analysis in Python. Expand your skillset by learning scientific computing with numpy.
Take the course on Introduction to Python on DataCamp here https://bit.ly/datacamp-intro-to-python
https://www.youtube.com/watch?v=67pqIGhvGAo”]
You can also watch the video on YouTube here.
Separate even and odd numbers in a list – Code Visualization
Ad:
Learn Python Programming Masterclass – Enroll Now.
Udemy
Task:
Separate even and odd numbers from a list and add them to new lists.
Approach:
- Read the input number asking for the length of the list using
input()
- Initialize an empty list
numbers = []
- Read each number using a
for loop
- In the for loop append each number to the list
numbers
- Create another two empty lists
even_lst = []
andodd_lst = []
- Now run another for loop to check the numbers in the list are divided by 2 or not
- If the numbers are divided by 2, append those elements to
even_lst
else append those toodd_lst
- Print both the
even_lst
andodd_lst
Program:
__author__ = 'Avinash' numbers = [] n = int(input("Enter number of elements: \t")) for i in range(1, n+1): allElements = int(input("Enter element:")) numbers.append(allElements) even_lst = [] odd_lst = [] for j in numbers: if j % 2 == 0: even_lst.append(j) else: odd_lst.append(j) print("Even numbers list \t", even_lst) print("Odd numbers list \t", odd_lst)
Output:
Course Suggestion
Want to learn python with strong fundamentals? If yes, I strongly suggest you to take the course below.
Course: Fundamentals of Programming in Python
For more programs on List datatype chek the posts below or click here for all programs related to lists.
- Python program to merge or concatenate two lists
- Find the Biggest and Smallest of 3 numbers using lists in Python
- Python Lists – Add, Append, Modify, Remove, Slice
- Python program to calculate the sum of elements in a list
- Python program to find the largest and smallest number in a list
- How to find Union of two lists in Python
- Python Program to separate even and odd numbers in a list
Ad:
Learn Python Programming Masterclass – Enroll Now.
Udemy