Home > other >  Replacing slice by an iterable
Replacing slice by an iterable

Time:03-21

I have a list s which looks as below:

s = [1, 2, 3]

I am replacing slice of 's' using below code:

s[1:4] = [22, 3, 4, 5, 6, 7]
print(s)

Output: [1, 22, 3, 4, 5, 6, 7]

My understanding s[1:4] should replace only 3 elements starting from 1st element and up to but not including 4th element.

Assumed Output: [1, 22, 3, 4]

CodePudding user response:

So let's use a better example. I've included the output as commented out code in the code snippets

s = list(range(1, 11))
print(f"Len = {len(s)} | S = {s}")

# Len = 10 | S = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

There are 3 scenarios:

Case 1: Assigned list is shorter than the index range

s = list(range(1, 11))
s[1:4] = [0, 0]
print(f"Len = {len(s)} | S = {s}")

# Len = 9 | S = [1, 0, 0, 5, 6, 7, 8, 9, 10]

Ans : The list size is shrunk by 1 since only 2 items are being assigned to 3 places.

Case 2: Assigned list is longer than the index range

s = list(range(1, 11))
s[1:4] = [0, 0, 0, 0, 0, 0, 0]
print(f"Len = {len(s)} | S = {s}")

# Len = 14 | S = [1, 0, 0, 0, 0, 0, 0, 0, 5, 6, 7, 8, 9, 10]

Ans : The list size is increased by 4 since 7 items are being assigned to 3 places.

Case 3: Assigned list is equal to index range

s = list(range(1, 11))
s[1:4] = [0, 0, 0]
print(f"Len = {len(s)} | S = {s}")

# Len = 10 | S = [1, 0, 0, 0, 5, 6, 7, 8, 9, 10]

Ans : In this case it will be replaced properly since both the sizes match.

Conclusion

  • Python seems to be shrinking and growing the list to accommodate the assigned items.
  • All elements outside the slice indices will not be affected regardless of how big/small the assigned list is.

Update

As @mealhour pointed out there is a fourth case where you can increase the step size to be greater than 1 and assign it to every kth item in the list. In this case, the sizes have to match otherwise, python throws an error. This StackOverflow question explains it really well

s = list(range(1, 11))
# s[1:4:2] = [0, 0, 0] <- This throws an error
s[1:4:2] = [0, 0]
print(f"Len = {len(s)} | S = {s}")

# Len = 10 | S = [1, 0, 3, 0, 5, 6, 7, 8, 9, 10]

CodePudding user response:

s = [1,2,3]
x = [22,3,4,5,6]
j = 0
for i in range(1,4):
    try:
        s[i] = x[j]
    except IndexError:
        s.append(x[j])
    j  =1

You can use something like this to achieve your goal

  • Related