by: Cobena Isaac

How to perform operations across multiple lists and output an updated list for each one

How to perform operations across multiple lists and output an updated list for each one

When working with multiple lists in Python, you often need to apply the same cleaning operations to each one and permanently update them. Instead of processing each list individually, you can clean them all efficiently in a loop.

Example 1:

Let’s say you have lists with messy strings containing extra spaces, and you want to clean them: - convert all words to lowercase, while keeping the results as separate lists.

1
2
List_A = [" Apple ", "banana ", " Cherry"]
List_B = [" Grape", "orange ", " PEAR "]

You can achieve this using the following solutions:

1
2
3
4
5
# Step 1: Combine your lists into one list of lists
Lists = [List_A, List_B]

# Step 2: Clean all lists using a list comprehension
cleaned_lists = [[s.strip().lower() for s in lst] for lst in Lists]

Then, unpack the results into separate lists or variable names

1
2
# Step 3: Unpack the results back into separate variables
List_A, List_B = cleaned_lists

Now print both lists to see the permanenetly cleaned results.

1
2
print(List_A)  # Output: ['apple', 'banana', 'cherry']
print(List_B)  # Output: ['grape', 'orange', 'pear']
Example 2:

Assume, you want to remove "x" character from the original Lists directly (instead of creating new ones) to obtain permanently cleaned Lists, use slice assignment.

Example:

Removing unwanted characters and deduplicating

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import re

# Example messy lists with unwanted 'x' characters
List1 = ['myoxcardial', 'anoxemia', 'dixabetes']
List2 = ['exzema', 'xdata', 'myoxpathy']

# Combine lists for processing
Lists = [List1, List2]

# Clean each list in-place
for list in Lists:
    # Remove all 'x' characters using regex
    list[:] = [re.sub('x', ' ', i) for i in list]
    # Remove duplicates by converting to set and back to list
    list[:] = set(list) 

Let’s print out the cleaned lists:

1
2
print(List1)  # Output: ['myocardial', 'anemia', 'diabetes']
print(List2)  # Output: ['eczema', 'data', 'myopathy']
  • Use lst[:] when you want to modify the original list in-place.
  • Using list comprehensions are perfect for applying the same operation to every item

You can efficiently clean any number of lists using these patterns! Try them with your own data cleaning tasks.

Hope this tutorial helps! Read our other tutorials to learn more.