0

I cannot understand what this line means:

queue = [list() for _ in range(k)]

This is the full code:

for i in range(1, maxlen+1):     
    queue = [list() for _ in range(k)]   
    for word in words:

        word += (maxlen - len(word)) * ' '

        if ord(word[-i]) >= 97:
            queue[ord(word[-i]) - (97)].append(word)
        else:
            queue[0].append(word)


    words = sum(queue, [])

for i in range(len(words)):
    words[i] = words[i].replace(" ", "")

print(words)
bfontaine
  • 18,169
  • 13
  • 73
  • 107

4 Answers4

1

That simply just creates a list the number of the variable k times of a empty list, so see example:

a=3
print([list() for i in range(a)])

Output:

[[], [], []]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0
queue = [list() for _ in range(k)]

it is creating a list of empty lists which is called queue. Queue is a list containing k empty lists

Vaibhav Sahu
  • 344
  • 2
  • 8
0

_ is simply a variable such as i or j. You are using an underscore to show that it is a throwaway varaible which you do not use again.

See also What is the purpose of the single underscore "_" variable in Python?

tfv
  • 6,016
  • 4
  • 36
  • 67
0

This is python’s list comprehension, which is shortened code for

queue = []
for _ in range(k):
    queue.append(list())

underscore _ is a python variable meant to represent the last accessed variable and typically is used as a throwaway variable that the script code does not wish to reference

ycx
  • 3,155
  • 3
  • 14
  • 26