2

I am creating a dice program that must roll the dice a certain amount of times and append those rolls to a list. I am trying to figure out how to add commas in between each item of the list. This is the code that I have so far:

listRolls = []

def listPrint():
    for i, item in enumerate(listRolls):
        if (i+1)%13 == 0:
            print(item)
        else:
            print(item,end=' ')
  • not a good dupe. its concattenating _strings_ not printing - you could create strings from numbers and concattenate but thats not even needed here – Patrick Artner Oct 06 '18 at 06:43

3 Answers3

3

print(', '.join(listRolls))

For future reference, it's more "pythonic" (not my word) to use lower case variable_names, meaning your listRolls would then be list_rolls. Your code will handle it JUST FINE, however!

UtahJarhead
  • 2,091
  • 1
  • 14
  • 21
1

change

print(item,end=' ') 

into

print(item,end=',')
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

If you want to print your whole list in one line, komma seperated simply use

data = [2,3,4,5,6]

print( *data, sep=",")

The * before the list-variable will make single elements from your list (decomposing it), so the print command essentially sees:

print( 2,3,4,5,6 , sep=",")

The sep="," tells the print command to print all given elements with a seperator as specified instead of the default ' '.

If you need to print, say, only 4 consecutive elements from your list on one line, then you can slice your list accordingly:

data = [2,3,4,5,6,7,8,9,10,11]

# slice the list in parts of length 4 and print those:
for d in ( data[i:i+4] for i in range(0,len(data),4)):
    print( *d, sep=",")

Output:

2,3,4,5
6,7,8,9
10,11

Doku:

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69