Python list comprehension if-else
if...else in Python List ComprehensionPython Python List Created: January-31, 2021 | Updated: July-18, 2021 Show This tutorial will explain multiple ways to perform list comprehension with the if ... else statement in Python. A list comprehension is a short and syntactic way to create a list based on an existing list. It is usually used to create a new filtered or changed list from a current list. For example, we have a python list ['Ali','Mark', None, 'Sara', None, 'Rahul'] and we want to create a new list ['Ali','Mark', '', 'Sara', '', 'Rahul'], we can do it by using list comprehension. Python if ... else List ComprehensionThe below example code demonstrates how we can create a changed list from the existing list using list comprehension with the if ... else statement: Output: ['Ali', 'Mark', '', 'Sara', '', 'Rahul']The general syntax of list comprehension in Python with if ... else is: If condition is true for the list element x, f(x), any applicable function, is applied to the element; otherwise, g(x) will be applied. Example code: my_list = ['Ali','Mark', None, 'Sara', None, 'Rahul'] new_list = [x.upper() if x is not None else '' for x in my_list] print(new_list)Output: ['ALI', 'MARK', '', 'SARA', '', 'RAHUL']Contribute DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page. Related Article - Python List
|