1

I have a list = [1, 2, 3]

I want this to be printed 1, 2, 3

However, when I use:

for number in list:
     print(num)

the number gets printed:

1

2

3
nguyendhn
  • 423
  • 1
  • 6
  • 19
Dylan
  • 103
  • 6
  • Technically, this is _not_ a duplicate. The OP implies that he would want to use a `for` loop construct. And none of the answers in the referred question provides a direct answer to this requirement. – lifebalance Jun 20 '20 at 03:03
  • @lifebalance Literally the first answer of that duplicate uses a loop. – Mark Rotteveel Jun 20 '20 at 10:28
  • @MarkRotteveel If that answer could be _trivially_ modified to provide for a `comma` separator (as indicated by the OP), I would have gladly linked to that answer myself, but that is not the case. – lifebalance Jun 20 '20 at 16:59

3 Answers3

1

For alist = [1, 2, 3]

print(alist)
# [1, 2, 3]

If you don't want the square brackets,

print(', '.join(str(i) for i in alist)
# 1, 2, 3

If you want to print only the elements,

print (*alist)
# 1 2 3

If you insist on using a for loop,

for i in alist[:-1]: 
    print(i, end = ", ")
print(alist[-1])
# 1, 2, 3
lifebalance
  • 1,846
  • 3
  • 25
  • 57
1

It sounds like you are asking for the string.join function

items = [1, 2, 3]
print(', '.join(map(str, items))

which would give

1, 2, 3
Cireo
  • 4,197
  • 1
  • 19
  • 24
0

You can simply do

list = [1, 2, 3]
print(list)

If you code a "print" inside the "for" loop, the print will be called according to the number of items inside your list, and since each "print" you call, prints in each line, that´s the expected result.

Note to self: I shouldn't use list because it will shadow the builtin list object.

KdmJapa
  • 68
  • 6