Reputation: 929
I have a list such as:
myList = [1, 0, 0, 0, 1, 2]
I would like to print this as set listing notation:
{1, 0, 0, 0, 1, 2}
However, when I try to print this as a set, the duplicates are removed:
>>> set(mylist)
{0, 1, 2}
I do not want the duplicates to be removed. How can I print with set syntax, but without removing any duplicates?
Upvotes: 0
Views: 57
Reputation: 309929
Seems like simple string manipulation would work:
list_str = str(mylist).replace('[', '{').replace(']', '}')
Or, perhaps even better, we can just slice off the first and last characters of the list formatted string and replace them with the new braces that you want:
list_str = '{%s}' % (str(mylist)[1:-1])
This is better for the obvious reason that it doesn't have a chance to mess with the contents of the list (imagine using the previous code if your list contained strings that may or may not have '['
characters embedded in them).
If that still doesn't sit well with you, you can format the whole string yourself in a number of ways (usually involving getting a string representation of each item and joining them with a comma and space).
list_str = '{%s}' % (', '.join(repr(item) for item in mylist))
list_str = '{%s}' % (', '.join(map(repr, mylist)))
Upvotes: 7