1

I want to know what does list[:0] means. In the following code what it is doing?

LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
k=[]
while len(k) < 20:
    for i in LETTERS:
        k[:0] = i

print(k)

# k = ['Z', 'Y', 'X', 'W', 'V', 'U', 'T', 'S', 'R', 'Q', 'P', 'O', 'N', 'M', 'L', 'K', 'J', 'I', 'H', 'G', 'F', 'E', 'D', 'C', 'B', 'A']
  • Shouldn't the loop break when len(k)==20?
  • If k[:0] is an empty list, why every time there isn't a list inside k??
  • Does k[:0] works like a stack and pushes the older items?
blueteeth
  • 3,330
  • 1
  • 13
  • 23
  • Does this answer your question? [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – JacobIRR Jan 30 '20 at 22:30
  • `k[:0]` has a different meaning in a slice assignment than a slice expression. – Barmar Jan 30 '20 at 22:37
  • Your loop doesn't break because it runs the full ```for``` loop once and then checks the length of ```k```. – Lapis Rose Jan 30 '20 at 22:39

1 Answers1

1

Kind of a weird one here. And hard to explain.

k[:0] is always talking about the empty range at the start of the list. In fact any slice of an empty list is an empty list.

Because it's a slice, it is iterable, although without any elements. Like setting multiple variables at once, it can be set to an iterable, but not single values.

k[:0] = '123'  # puts '1', '2', '3' at the start
k[:0] = 123    # TypeError

The while loop doesn't really do anything, because the for loop runs through everything in LETTERS, and then breaks the condition.

The steps in your program are:

  1. Initialise an empty list
  2. Set the empty range at the start of the list ([]) to ['A']
  3. Repeat for all other letters.
  4. The list is now 26 elements long, so we don't get to the next iteration of the while loop.
blueteeth
  • 3,330
  • 1
  • 13
  • 23