list comprehension with a multiple condition if the element contains a particular string in python

You can use a multiple condition in a list comprehension to check if an element contains a particular string in Python. Here is the syntax for a list comprehension with multiple conditions:

main.py
# Syntax
new_list = [expression for item in iterable if condition1 and condition2]

# Example
original_list = ["apple", "banana", "cherry", "date"]
substring = "an"
new_list = [item for item in original_list if substring in item and len(item) > 4]
248 chars
8 lines

In the example above, we are creating a new list (new_list) using a list comprehension. The list comprehension checks whether each element in the original_list contains the substring "an" and has a length greater than 4. If both conditions are true, the element is included in the new_list.

So, after executing the code, new_list will contain ["banana", "cherry"] because only these elements satisfy both conditions.

Note that you can have any number of conditions and use various logical operators (and, or, not) to combine them as per your requirements.

I hope this helps! Let me know if you have any further questions.

related categories

gistlibby LogSnag