Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python List Comprehension Using If-Else
Next article icon

Python List Comprehension Using If-Else

Last Updated : 05 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

List comprehension with if-else in Python is a concise way to apply conditional logic while creating a new list. It allows users to add elements based on specific conditions and even modify them before adding.

Using if-else Inside List Comprehension

This is the simplest and most efficient way to apply conditional logic directly. This applies the if-else condition directly in the list comprehension. Each number is checked for divisibility by 2, and either "Even" or "Odd" is added to the list.

Python
a = [1, 2, 3, 4, 5]   # Add 'Even' for even numbers, otherwise 'Odd' result = ['Even' if n % 2 == 0 else 'Odd' for n in a]   print(result)   

Output
['Odd', 'Even', 'Odd', 'Even', 'Odd'] 

Let's explore some other methods on how to use list comprehension using if-else

Table of Content

  • Using if Condition Only (Without else)
  • Nested if-else in List Comprehension

Using if Condition Only (Without else)

This method is used when elements are added only if the condition is met. Here, the if condition filters out numbers that do not meet the condition. Only even numbers are added to the new list.

Python
a = [1, 2, 3, 4, 5]    # Include only even numbers in the list result = [n for n in a if n % 2 == 0]   print(result)   

Output
[2, 4] 

Nested if-else in List Comprehension

Handle multiple conditions with nested logic. Using Nested if-else in List allows chaining of if-else conditions. It categorizes each number based on whether it is divisible by 2, 3, or neither.

Python
a = [1, 2, 3, 4, 5]    # Categorize numbers based on divisibility result = ['Divisible by 2' if n % 2 == 0 else 'Divisible by 3' if n % 3 == 0 else 'Other' for n in a]   print(result)   

Output
['Other', 'Divisible by 2', 'Divisible by 3', 'Divisible by 2', 'Other'] 

Next Article
Python List Comprehension Using If-Else

B

boora_harsha_vardhan
Improve
Article Tags :
  • Python
  • Python Programs
  • python-list
Practice Tags :
  • python
  • python-list

Similar Reads

    Python List Comprehension With Two Lists
    List comprehension allows us to generate new lists based on existing ones. Sometimes, we need to work with two lists together, performing operations or combining elements from both. Let's explore a few methods to use list comprehension with two lists.Using zip() with List ComprehensionOne of the mos
    3 min read
    Two For Loops in List Comprehension - Python
    List comprehension is a concise and readable way to create lists in Python. Using two for loops in list comprehension is a great way to handle nested iterations and generate complex lists. Using two for-loopsThis is the simplest and most efficient way to write two for loops in a list comprehension.
    2 min read
    4 Tips To Master Python List Comprehensions
    Python's list comprehensions offer a concise and powerful way to create lists. They allow you to express complex operations in a single line of code, making your code more readable and efficient. In this article, we will explore four tips to master Python list comprehensions with five commonly used
    4 min read
    Python - Test if string contains element from list
    Testing if string contains an element from list is checking whether any of the individual items in a list appear within a given string.Using any() with a generator expressionany() is the most efficient way to check if any element from the list is present in the list. Pythons = "Python is powerful an
    3 min read
    Python - Check if List contains elements in Range
    Checking if a list contains elements within a specific range is a common problem. In this article, we will various approaches to test if elements of a list fall within a given range in Python. Let's start with a simple method to Test whether a list contains elements in a range.Using any() Function -
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences