Home > Software design >  Dynamically changing a list while looping
Dynamically changing a list while looping

Time:05-01

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.

CodePudding user response:

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.

CodePudding user response:

Yes, there's a simple solution.

for i in range(len(nums)):
    nums[i] = current_element
    do_processing(nums)
    nums[i] = i

The other way, of course, is just to make a copy of the list.

for i in range(len(nums)):
    n1 = nums[:]
    n1[i] = current_element
    do_processing(n1)

CodePudding user response:

No fancy functions, just a for loop and a temporary variable.

for i in range(len(nums)):
  old_value = nums[i]
  nums[i] = current_element
  ...
  nums[i] = old_value

CodePudding user response:

nums.pop()
for i in range(len(nums) 1):
  nums.insert(i,current_element)
  print(nums)
  nums.remove(current_element)
  • Related