How to perform operations across multiple lists and output an updated list for each one
Often in Python, you may need to clean several lists of strings using the same operations inside a loop and save the results as permanently updated lists. You don’t need to keep the original lists — just store the cleaned versions separately.
For example, suppose you have the following lists of messy strings with extra spaces around the words:
List_A = [" Apple ", "banana ", " Cherry"]
List_B = [" Grape", "orange ", " PEAR "]
And suppose you want to remove the extra spaces around each word and convert all words to lowercase.
You can achieve this using the following solutions:
# Solution 1: The results are stored as separate cleaned lists.
List_A = [" Apple ", "banana ", " Cherry"]
List_B = [" Grape", "orange ", " PEAR "]
Lists = [List_A, List_B]
cleaned_lists = [[s.strip().lower() for s in list] for list in Lists]
Then, unpack the results into separate lists or variable names
List_A, List_B = cleaned_lists # Unpack to get seperate names
Now print both lists to see the permanenetly cleaned results.
print(List_A)
['apple', 'banana', 'cherry']
print(List_B)
['grape', 'orange', 'pear']
Example 2: When you want to remove “x” from both lists and obtain permanently cleaned Lists.
import re
# Example messy lists
List1 = ['myoxcardial', 'anoxemia', 'dixabetes']
List2 = ['exzema', 'xdata', 'myoxpathy']
Lists = [List1, List2]
for list in Lists:
list[:] = [re.sub('x', ' ', i) for i in list]
list[:] = set(list)
Note that to modify the original lists, you should mutate them in place using slice assignment.
Let’s print out the cleaned lists:
print(List1)
['anoemia', 'diabetes', 'myocardial']
print(List2)
['ezema', 'data', 'myopathy']
Hope this tutorial helps! Read our other tutorials to learn more.