9

I need to print the sorted list of integers, but it should be in a line and without the list square brackets and without any '\n' in the end...

import random
n = int(input(""))
l=[]
for i in range(n):
    x = int(input())
    l.append(x)
not_sorted = True
while not_sorted:    
    x = random.randint(0,n-1)
    y = random.randint(0,n-1)
    while x==y:
        y = random.randint(0,n-1)
    if x>y:
        if l[x]<l[y]:
            (l[x],l[y])=(l[y],l[x])
    if x<y:
        if l[x]>l[y]:
            (l[x],l[y])=(l[y],l[x])
    for i in range(0,n-1):
        if l[i]>l[i+1]:
            break
    else:
       not_sorted = False
for i in range(n):
    print(l[i])

output should be like this::: 1 2 3 4 5 and not like this :::: [1,2,3,4,5]

Fabián Montero
  • 1,613
  • 1
  • 16
  • 34
Hououin Kyouma
  • 163
  • 1
  • 2
  • 8

5 Answers5

31

You can unpack the list to print using * which will automatically split by a space

print(*l)

if you want a comma, use the sep= argument

print(*l, sep=', ')
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
  • 2
    Is this only for Python 3.0 and later? This doesn't work for Python 2.7 – SQA777 Jul 08 '21 at 01:22
  • why on earth are you still using python 2.7?! It's over 10 years old! If you want to do this on python 2, you'll need to do `from __future__ import print_function`. – FHTMitchell Jul 13 '21 at 13:24
  • 1
    There are some Python packages that changed in Python 3.0, which would require a not-insignificant code change. Yes, Python 2.7 is over 10 years old. For 10+ years, I wrote code in Python 2.7. The code didn't just upgrade automatically when Python 3.0 came along. – SQA777 Jul 15 '21 at 23:13
4

Use

for i in range(n):
    print(l[i], end=' ')

Or

print(*l, end=' ')
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
-1

You can use join and list comprehensions for that. The only thing, items in a list should be strings, not integers

import random

n = int(input(""))
l = []

for i in range(n):
    x = int(input())
    l.append(x)

not_sorted = True

while not_sorted:    
    x = random.randint(0, n-1)
    y = random.randint(0, n-1)
    while x == y:
        y = random.randint(0, n-1)
    if x > y:
        if l[x] < l[y]:
            (l[x], l[y]) = (l[y], l[x])
    if x < y:
        if l[x] > l[y]:
            (l[x], l[y]) = (l[y], l[x])

    for i in range(0, n-1):
        if l[i] > l[i+1]:
            break
    else:
       not_sorted = False

print(', '.join([str(l[i]) for i in range(n)]))
wowkin2
  • 5,895
  • 5
  • 23
  • 66
-1

For the list of string, I do it this way....

listChar = ["a", "b", "c", "d"]

someChar = ""

for n in listChar:
  someChar = someChar + n

print(someChar)

Res: abcd
Matej89
  • 1
  • 1
-1

Use enumerate to generate count(0-indexed) for each value. To print them on the same line use can use the end keyword

    for idx, val in enumerate(list_name):
         print(val, end = " ")