0

I'm generating a list of random digits, but I'm struggling to figure out how to output the digits in a single row without the square brackets?

import random 
def generateAnswer(answerList):

    listofDigits = []
    while len(listofDigits) < 5:
        digit = random.randint(1, 9)
        if digit not in listofDigits:
            listofDigits.append(digit)
    return listofDigits

def main():
    listofDigits = []
    print(generateAnswer(listofDigits))

main()
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Carstairs
  • 63
  • 4
  • Hi, there are a few optimizations you can do. Please check out my answer :) – Pinyi Wang Nov 02 '18 at 01:35
  • Does this answer your question? [Print list without brackets in a single row](https://stackoverflow.com/questions/11178061/print-list-without-brackets-in-a-single-row) – Gino Mempin Jan 03 '22 at 23:50

4 Answers4

4
print(", ".join([str(i) for i in generateAnswer(listofDigits)]))
tike
  • 2,234
  • 17
  • 19
4

You can unpack a list and use the sep argument:

print(*generateAnswer(listofDigits), sep=' ')
jpp
  • 159,742
  • 34
  • 281
  • 339
3

Try this:

listofDigits = []
print(str(generateAnswer(listofDigits))[1:-1])

Also, if generateAnswer initialize and return the list, then you don't need to pass in an empty list. Another thing is that if you want to generate a non-repeating random list, you can use random.sample and range.

I think this is better:

import random 
def generateAnswer():
    return random.sample(range(1, 10), 5)

def main():
    print(str(generateAnswer())[1:-1])

main()

Hope it helps!

Pinyi Wang
  • 823
  • 5
  • 14
1

The reason you’re getting the brackets is because the list class, by default, prints the brackets. To remove the brackets, either use a loop or string.join:

>>> print(' '.join(map(str, listofDigits)))
9 2 1 8 6
>>> for i in listofDigits:
    print(i, end=' ')


9 2 1 8 6 

Note that the last method adds a space at the end.

Note that in the first method, the arguments need to be cast to strings because you can only join strings, not ints.

rassar
  • 5,412
  • 3
  • 25
  • 41