-1

How to iterate through the while loop and display the contents of a list, tuple or any other collection in the same line, separated by commas ensuring that the comma is not displayed at the end?

Example:

def display(a):
    i=0
    while(i<len(a)):
        print(a[i],end=",")
        i+=1

a=(10,20,30)
display(a)

Output should be : 10,20,30 But i get 10,20,30, Please give answers other than the method of using ','.join(map(str(a)) or stripping the space by converting it to a string.

Sasikala
  • 9
  • 5

1 Answers1

0

You could print the items and then print the commas.

def display(a):
    i=0
    while(i<(len(a))):
        print(a[i],end="")
        if(i<(len(a)-1)):
            print(",", end="")
        i += 1

a = (10,20,30)
display(a)

Another way could be the following:

def display(a):
    print(*a, sep=",")

a = (10,20,30)
display(a)

Both ways print out: 10,20,30

George Bou
  • 568
  • 1
  • 8
  • 17