Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing slice by an iterable

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]

>Solution :

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

s = list(np.arange(1, 11, 1))
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(np.arange(1, 11, 1))
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(np.arange(1, 11, 1))
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(np.arange(1, 11, 1))
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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading