I would like to propose adding a new built-in method to Python lists for swapping two specific values: list.swap_values(v1, v2, all_occurrences=True).
Currently, swapping values within a list requires complex loops or long list comprehensions. I have designed a solution that allows developers to easily swap all matching values or choose to swap only the first occurrence of each value by setting all_occurrences=False.
Here is the code that shows how this feature should behave:
class Switchlist:
def __init__(self,existing_list):
self.list = existing_list
def swap_values(self,v1,v2,all_occurrences=True):
if all_occurrences:
return [v2 if x==v1 else v1 if x==v2 else x for x in self.list]
new_list=[]
changed_v1=False
changed_v2=False
for item in self.list:
if item==v1 and not changed_v1:
new_list.append(v2)
changed_v1=True
elif item==v2 and not changed_v2:
new_list.append(v1)
changed_v2=True
else:
new_list.append(item)
return new_list
# Example for both cases:
my_list=["a","b","c","a","b","d"]
sm_all=Switchlist(my_list).swap_values("a","b")
print(f"Original list: {my_list}")
print(f"New list (all): {sm_all}")
# Output: ['b','a','c','b','a','d']
# Swapping only the first occurrence
sm_first=Switchlist(my_list).swap_values("a","b",all_occurrences=False)
print(f"New list (first only): {sm_first}")
# Output: ['b','a','c','a','b','d']
I believe making this a built-in method would make the code more readable for everyone and especially beginners