It's also possible to use str.format() to join values in a list by unpacking the list inside format() which inserts the values sequentially into the placeholders. It can handle non-strings as well.
lst1 = ['this', 'is', 'a', 'sentence'] lst2 = ['numbers', 1, 2, 3] '{}-{}-{}-{}'.format(*lst1) # 'this-is-a-sentence' '{} {}, {} and {}'.format(*lst2) # 'numbers 1, 2 and 3'
For a large list, we can use the list's length to initialize the appropriate number of placeholders. One of two ways could be used to do that:
-
', '.join(['{}']*len(lst)).format(*lst)
-
('{}, '*len(lst)).rstrip(', ').format(*lst)
A working example:
lst = [1.2345, 3.4567, 4.567, 5.6789, 7.8] ', '.join(['{}']*len(lst)).format(*lst) # '1.2345, 3.4567, 4.567, 5.6789, 7.8' ('{}, '*len(lst)).format(*lst).rstrip(', ') # with a float format specification ', '.join(['{:.2f}']*len(lst)).format(*lst) # '1.23, 3.46, 4.57, 5.68, 7.80'