85.2k views
3 votes
How to add commas in the list of numbers in a list python?

The list is very large to manually add commas in the list.

User Jbrtrnd
by
6.5k points

1 Answer

0 votes

Answer: Here are two ways you can do it.

Step-by-step explanation:

One way to add commas in a list of numbers in Python is to use the 'join()' method.

Here is an example:

numbers = [1, 2, 3, 4, 5]

print(', '.join(map(str, numbers)))

This will output: "1, 2, 3, 4, 5"

Another way is to use list comprehension to create a new list of numbers with commas between them as following:

numbers = [1, 2, 3, 4, 5]

comma_separated_numbers = [str(number) + ", " for number in numbers]

print("".join(comma_separated_numbers)[:-2])

This will also output: "1, 2, 3, 4, 5"

You can use either way that you think is more elegant and readable for your use case.

In this : You can use the 'join()' method to add commas in between each number in the list. Here is an example:

list = [72, 3, 93, 94, 57, 54, 89, 46, 9, 61, 14, 2, 56, 65, 76, 10, 7, 51, 70, 71, 37, 28, 38, 16, 11, 33, 24, 95, 75, 20, 45, 55, 58, 5, 73, 26, 21, 62, 41, 19, 1, 32, 39, 96, 98, 79, 12, 23, 47, 88, 85, 90, 99, 52, 81, 4, 86, 91, 53, 97, 67, 43, 44, 22, 49, 17, 69, 68, 34, 59, 78, 84, 64, 66, 80, 92, 100, 82, 48, 77, 31, 25, 42, 30, 6, 87, 74, 29, 35, 60, 50, 8, 13, 63, 15, 36, 83, 18, 27, 40]

print(', '.join(map(str, list)))

This will output: "72, 3, 93, 94, 57, 54, 89, 46, 9, 61, 14, 2, 56, 65, 76, 10, 7, 51, 70, 71, 37, 28, 38, 16, 11, 33, 24, 95, 75, 20, 45, 55, 58, 5, 73, 26, 21, 62, 41, 19, 1, 32, 39, 96, 98, 79, 12, 23, 47, 88, 85, 90, 99, 52, 81, 4, 86, 91, 53, 97, 67, 43, 44, 22, 49, 17, 69, 68, 34, 59, 78, 84, 64, 66, 80, 92, 100, 82, 48, 77, 31, 25, 42, 30, 6, 87, 74, 29, 35, 60, 50, 8, 13, 63, 15, 36, 83, 18, 27, 40"

You could also use list comprehension to create a new list of numbers with commas between them as following:

comma_separated_numbers = [str(number) + ", " for number in list]

print("".join(comma_separated_numbers)[:-2])

This will also output: "72, 3, 93, 94, 57, 54, 89, 46, 9, 61, 14, 2, 56, 65, 76, 10, 7, 51, 70, 71, 37, 28, 38, 16, 11, 33, 24, 95, 75, 20, 45, 55, 58, 5, 73, 26, 21, 62, 41, 19, 1, 32, 39, 96, 98, 79, 12, 23, 47, 88, 85, 90, 99, 52, 81, 4, 86, 91, 53, 97, 67, 43, 44, 22, 49, 17, 69, 68, 34, 59, 78, 84, 64, 66, 80, 92, 100, 82, 48, 77, 31, 25, 42, 30, 6, 87, 74, 29, 35, 60, 50, 8, 13, 63, 15, 36, 83, 18, 27, 40"

You can use either way that you think is more elegant and readable for your use case.

User Derfder
by
7.3k points