Reputation: 79
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=' ')
Upvotes: 2
Views: 4753
Reputation: 51643
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:
Upvotes: 0
Reputation: 2217
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!
Upvotes: 3