Slice Assignment in Python

What is the output of this code snippet?


customers = [‘Marie’, ‘Anne’, ‘Donald’]
customers[2:4] = [‘Barack’, ‘Olivia’, ‘Sophia’]


A great coder seeks the cleanest and shortest way to accomplish his goals. This puzzle demonstrates a Python trick that I found very useful: slice assignments.

Suppose you work in a biotech startup on DNA sequence modeling. You maintain different DNA sequences as lists of string values. To simulate recombinations of DNA sequences, you change subsequences of the list on a regular basis. In this case, slicing is your best friend: It helps you to read specific subsequences. Moreover, slice assignments enable you to replace, append, or clear whole subsequences.

In the puzzle, we have a list of customers that are partially replaced by new customers. The puzzle shows how the length of the original sequence may change due to the slice assignment. Note that we can even clear the list with “customers[:] = []”. These powerful operations cost only a single line of code.


Are you a master coder?
Test your skills now!


Related Video


[‘Barack’, ‘Olivia’]


Leave a Comment

Your email address will not be published. Required fields are marked *