How to remove repetitions from a list? | Projectshop.in

We can remove repetitions from a list by converting it to a set, as sets automatically discard duplicate elements. However, sets do not preserve the order of elements. If maintaining the order of elements is important, you’ll need a different approach.

1. Using a Set

Here’s how to remove duplicates using a set:

Python
# Original list
thislist = ["apple", "banana", "cherry", "banana"]

# Remove duplicates using a set
unique_set = set(thislist)

# Convert the set back to a list
unique_list = list(unique_set)

# Print the result
print(unique_list)

Explanation:

  • set(thislist) converts the list to a set, removing any duplicates.
  • list(unique_set) converts the set back to a list.

Output:

Bash
['apple', 'cherry', 'banana']  # Order may vary

2. Preserving Order While Removing Duplicates

If you need to remove duplicates while preserving the order of elements, you can use a loop with a set to keep track of seen elements:

Python
# Original list
thislist = ["apple", "banana", "cherry", "banana"]

# Remove duplicates while preserving order
seen = set()
unique_list = []
for item in thislist:
    if item not in seen:
        unique_list.append(item)
        seen.add(item)

# Print the result
print(unique_list)

Explanation:

  • seen Set: Keeps track of elements that have already been added to the unique_list.
  • Loop: Iterates over the original list, adding each element to the unique_list only if it hasn’t been added before.

Output:

Bash
['apple', 'banana', 'cherry']

Using the order-preserving approach ensures that the original order of elements is maintained while removing duplicates.

These methods are efficient and easy to understand, allowing you to remove repetitions from a list effectively.

Read Also : How to check if any element from list2 is present in list1

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart