How to Remove Elements from a List Based on Length in Python?

Estimated read time 1 min read

To remove elements from a list based on their length in Python, you can use a list comprehension that filters elements based on a condition. Here is an example code snippet that removes elements from a list based on their length:

original_list = ["apple", "banana", "cherry", "date", "elderberry"]

# Remove elements from the list based on length
new_list = [element for element in original_list if len(element) < 6]

print(new_list)  # Output: ['apple', 'date']

In this code, we define an original list (original_list) that contains elements.

Next, we create a new list (new_list) using a list comprehension that filters elements from the original list based on their length. The len(element) < 6 condition is used to filter out elements whose length is greater than or equal to 6.

Finally, we print the new list (new_list) that contains elements after removing elements based on their length.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply