0

I'm trying to print a list with {} curly braces. For example:

the_list = [1, 2, 3]

and I want to print the list as

{1, 2, 3}

How can I do that? Thanks!

Baran
  • 29
  • 1
  • 5

7 Answers7

6

You can do this like this:

print('{' + ', '.join([str(x) for x in the_list]) + '}')

', '.join joins each element with a ', '

[str(x) for x in the_list] makes each number a string so it can be joined as above.

9000
  • 39,899
  • 9
  • 66
  • 104
Ryan Schaefer
  • 3,047
  • 1
  • 26
  • 46
5

print(str(list).replace('[','{').replace(']','}'))

this converts the list to a string and replaces "[]" with "{}"

Garret
  • 144
  • 12
  • This is a hack on the representation of the list. Please use the items of the list instead. – Samuel GIFFARD Mar 12 '18 at 17:25
  • 2
    this works for op so its good enough... simple question simple answer no need for complexity @SamuelGIFFARD – Garret Mar 12 '18 at 17:27
  • 1
    3.x question should get answer for 3.x – Terry Jan Reedy Mar 12 '18 at 17:30
  • No, it's a _complex_ answer, because it goes against the nature of the data structure and uses irrelevant details. It's also slow. – 9000 Mar 12 '18 at 17:30
  • 2
    @9000 No, it is faster. I measured using timeit. For the short list of 3, this method takes 3/4 of the time required for GIFFARDS map answer. For long lists (10000) the advantage grows to 1/2 the time (twice as fast). – Terry Jan Reedy Mar 12 '18 at 17:51
  • 1
    At least someone comes with some actual proof and it proves me right nice try ;) thanks for the info @TerryJanReedy – Garret Mar 12 '18 at 17:53
  • @TerryJanReedy: I ran `timeit`, and I stand corrected! Indeed, apparently both `str(list)` and `str.replace` are very optimized in Python, and iteration / generation using explicit function calls is pretty expensive in comparison. – 9000 Mar 12 '18 at 19:17
5

In Python 2, try:

my_list = [1, 2, 3]
print '{{{}}}'.format(', '.join(map(str, my_list)))

In Python 3, try:

my_list = [1, 2, 3]
print(f'{{{", ".join(map(str, my_list))}}}')

Explanation:

Format

Whenever you're looking to get one of your objects in a specific format, check .format() https://docs.python.org/2/library/stdtypes.html#str.format

It uses {} as placeholders (can be made more complex, that's just a simple example). And to escape { and }, just double it, like so: "{{ }}". This latter string, after formatting, will become "{ }".

In Python 3, you now have f-strings https://www.python.org/dev/peps/pep-0498/ They work the same as ''.format() but they are more readable: ''.format() => f''.

Casting elements into str

Then, you want all your elements (in the list) to be transformed into strings -> map(str, my_list).

Joining elements

And then, you want to glue each of these elements with ", ". In Python, there is a function that does just that: https://docs.python.org/2/library/stdtypes.html#str.join

', '.join(my_iterable) will do it.

Reserved keywords

And last but not least, do not name your list list. Otherwise, you'll rewrite the builtin list and you won't be able to use lists anymore. Check this answer for a good list of these keywords: https://stackoverflow.com/a/22864250/8933502

Samuel GIFFARD
  • 796
  • 6
  • 22
1

If you want to get hacky:

>>> l = [1, 2, 3]
>>> '{%s}' % str(l).strip('[]')
>>> {1, 2, 3}
user3483203
  • 50,081
  • 9
  • 65
  • 94
1

There are two approaches to answering this question:

A. Modify str(alist) by replacing [] with {}. @Garret modified the str result calling str.replace twice. Another approach is to use str.translate to make both changes at once. A third, and the fastest I found, is to slice off [ and ], keep the content, and add on { and }.

B. Calculate what str(alist)[1:-1] calculates but in Python code and embed the result in {...}. With CPython, the multiple replacements proposed for building the content string are much slower:

import timeit

expressions = (  # Orderd by timing results, fastest first.
    "'{' + str(alist)[1:-1] + '}'",
    "str(alist).replace('[','{').replace(']','}')",
    "str(alist).translate(table)",
    "'{' + ', '.join(map(str, alist)) + '}'",
    "'{{{}}}'.format(', '.join(map(str, alist)))",
    "'{' + ', '.join(str(c) for c in alist) + '}'",
    )

alist = [1,2,3]
table = str.maketrans('[]', '{}')
for exp in expressions:
    print(eval(exp))  # Visually verify that exp works correctly.

alist = [1]*100  # The number can be varied.
n =1000
for exp in expressions:
    print(timeit.timeit(exp, number=n, globals=globals()))

Results with 64-bit 3.7.0b2 on Windows 10:

{1, 2, 3}
{1, 2, 3}
{1, 2, 3}
{1, 2, 3}
{1, 2, 3}
{1, 2, 3}
0.009153687000000021
0.009371952999999988
0.009818325999999988
0.018995990000000018
0.019342450999999983
0.028495214999999963

The relative results are about the same for 1000 and 10000.

EDIT: @Mike Müller independently posted the slice expression, embedded in the following two expressions, with essentially the same timings as the top expression above.

"f'{{{str(alist)[1:-1]}}}'",
"'{%s}' % str(alist)[1:-1]",
Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
0
('{}'.format(the_list)).replace('[','{').replace(']','}')

Result

{1, 2, 3}
Bill Bell
  • 21,021
  • 5
  • 43
  • 58
0

Using Python 3.6 f-strings:

>>> lst = [1, 2, 3]
>>> print(f'{{{str(lst)[1:-1]}}}')
{1, 2, 3}

or with format for Python < 3.6:

>>> print('{{{}}}'.format(str(lst)[1:-1]))
{1, 2, 3}

or with the old, but not deprecated %:

>>> print('{%s}' % str(lst)[1:-1])
{1, 2, 3}
Mike Müller
  • 82,630
  • 20
  • 166
  • 161