Print f list items in one line

Viewed 268

I would like to print the list in one line. I works with simple print, but it doesn´t work when it´s f print. How could I do that, please? Thank you

list = ["A", "B", "C"]

print(*[n for n in list], sep=", ")

print(f"Item was added: {*[n for n in nazvy]}")
4 Answers

Use ' '.join

l = ["A", "B", "C"]
print(', '.join(l))
print(f"Item was added: {', '.join(l)}")

Output

A, B, C
Item was added: A, B, C

NOTE: Try not to use in-built keywords as variable names. Eg: list


Your code didn't work because f-string doesn't allow starred expression or unpacking.

Meanwhile

print(*[n for n in list], sep=", ")

worked because it translates to below due to list unpacking

print('A', 'B', 'C', sep=", ")

Use "end=" instead of "sep=";

list = ["A", "B", "C"]
for x in list:
   print(x, end=', ')

You can use *list to send each value to print statement. With this approach, you don't have to worry about converting data to string.

With that, you can just give

mylist = ["A", "B", "C", 4, 5, 6]

print(*my_list, sep=", ")

The output of this will be:

A, B, C, 4, 5, 6

If you want to use the fstring, you can also try giving:

print(f'{*mylist,}')

The output of this will be:

('A', 'B', 'C', 4, 5, 6)

Note here that it prints with brackets ().

For more details about unpacking f-string, see the post on Stackoverflow here

Also please try to avoid naming variables as list. It will get confusing later when you want to convert data to a list.

Example:

x = {1:5,2:10,3:15}
y = list(x)
print (y)

will convert dictionary x to a list y

Related