Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically changing a list while looping

Tags:

python

arrays

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.

like image 557
wannabeprogrammer Avatar asked Apr 11 '26 11:04

wannabeprogrammer


1 Answers

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.
like image 155
BrokenBenchmark Avatar answered Apr 13 '26 00:04

BrokenBenchmark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!