Python: How to not print comma in last element in a for loop?
My code iterates over a set and print actor's names: for actor in actorsByMovies(): print actor+",", The result looks like: Brad Pitt, George Clooney, But I want it to detect the last element so that it won't print the last comma. The result should be instead: Brad Pitt, George Clooney How can I do that?
print ', '.join(actorsByMovies())
The solution by @jamylak is best whenever you can use it, but if you have to keep the loop for other things, you might do something like this:
from __future__ import print_function # Python [2.6, 3) for index, actor in enumerate(actorsByMovies()): if index > 0: print(', ', end='') print(actor, end='')
Using the same new
print(*actorsByMovies(), sep=', ')
- Database Administration Tutorials
- Programming Tutorials & IT News
- Linux & DevOps World
- Entertainment & General News
- Games & eSport