How to Trim All Elements of a List in Python

In this tutorial, we’ll cover how to trim all elements of a list in Python. It is common in programming to receive lists with whitespace characters that you may want to remove for different purposes such as cleanup, better reading, or to properly use these strings in other functions.

Python provides several methods to tackle these issues, one of which is via the strip() function. The strip() function is used to remove leading and trailing whitespace characters.

What are whitespace characters?

Whitespace characters in Python, or in any programming language, are characters that represent horizontal or vertical space in typography. It’s basically the space that you cannot see but takes space. Whitespace includes spaces, tabs(‘\t’), newlines(‘\n’), etc.

Step 1: Create a List

First, let’s start by creating a list of strings that contains leading and trailing whitespaces. This list will serve as an example for this tutorial.

Step 2: Using the strip() function to remove whitespaces

The strip() function in Python is used to remove leading and trailing whitespace characters from a string. To remove the whitespaces in all elements of a list, you can use a loop to traverse all the elements and apply the strip() function. However, Python provides a faster and more efficient way to do this using List Comprehension.

List comprehension is a concise way to create lists. It is a bracket containing an expression followed by a for statement and optionally one or more for or if statements.

Step 3: Print the new list

Finally, you can print your newly trimmed list to confirm that all the whitespaces have been removed.

Complete Code

Output

['birds', 'cats', 'dogs', 'horses']

Conclusion

In this tutorial, we learned how to trim all elements of a list in Python using the strip() function and list comprehension. The strip() function allows you to remove leading and trailing whitespace characters, which can be very handy when working with lists of strings in your programs.

List comprehension, on the other hand, provides a concise and efficient means to create a new list based on this transformation.