Slice List Assignments in Python

What is the output of this code snippet?

 

letters = ['a', 'b', 'c',
           'd', 'e', 'f', 'g']
letters[1:] = []
print(letters)

 

In verbose programming languages such as Java, you have to iterate over a list to remove subsequent elements. In Python, a simple one-liner does that for you. Use the slice notation to select a sequence of items in the list. This is the lefthand side of your equation. Then overwrite the selected sequence with the empty (or any other) list.
Because of this kind of clarity and simplicity, Python has become so popular nowadays.


Are you a master coder?
Test your skills now!

 

Related Video

Solution

[‘a’]

 

Leave a Comment