Skip to content

Dynamically changing a list while looping

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.

Answer

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:

  1. This doesn’t mutate the original list. If you need to access the original list for any reason, you can.
  2. You don’t need to worry about resetting values at the start/end of each iteration. If you need to implement this pattern several times, you don’t need to remember to replace the values each time.