I have a list:
nums = [0, 1, 2, 3]
what I would like to do is loop though this list but then change the list. Basically when I loop through nums = [0, 1, 2, 3] nums would need to change to:
nums = [current_element, 0, 1, 2]
nums = [0, current_element, 1, 2]
nums = [0, 1, current_element, 2]
nums = [0, 1, 2, current_element]
Is there a way of changing nums like this? I feel like there is a simple solution to this, but I've been stumped for hours.
You can pass a map() object to the for loop that generates the list you need at each iteration. For each index, we generate a new list using list slicing to replace the element at that index:
current_element = 42
nums = [0, 1, 2, 3]
for lst in map(lambda x: nums[:x] + [current_element] + nums[x+1:], range(len(nums))):
print(lst)
This outputs:
[42, 1, 2, 3]
[0, 42, 2, 3]
[0, 1, 42, 3]
[0, 1, 2, 42]
This approach has two notable advantages:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With