0

What does it "-1" in the loop mean

CAPACITY = 10
buffer = [-1 for i in range(CAPACITY)]

3 Answers3

4

That is the element of the list that will get created as part of the list-comprehension.

>>> l = [-1 for _ in range(5)]
>>> l
[-1, -1, -1, -1, -1]
>>> l[1] = 2
>>> l
[-1, 2, -1, -1, -1]

This specific example could also be written as [-1] * CAPACITY.

>>> l = [-1] * 5
>>> l
[-1, -1, -1, -1, -1]
>>> l[1] = 2
>>> l
[-1, 2, -1, -1, -1]
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Wasn't me, but it is not the same thing in general though (similar enough for immutable objects, I'll admit) – user2390182 Oct 26 '21 at 16:18
  • 1
    @user2390182 but in this particular case it accomplishes exactly the same so I would consider it to be _the same thing_ – Matiiss Oct 26 '21 at 16:19
2

This is a list comprehension - when expanded out it would be equivalent to:

buffer = []
for i in range(CAPACITY):
    buffer.append(-1)
match
  • 10,388
  • 3
  • 23
  • 41
0

That's a List Comprehension.

You are basically declaring a list of CAPACITY size with a for loop, all elements of that list will have a value of -1.

If you print(buffer), you will get the following output:

[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
BTables
  • 4,413
  • 2
  • 11
  • 30
rookie
  • 126
  • 10