Reputation: 313
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]
Upvotes: 10
Views: 36274
Reputation: 53
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 = " ")
Upvotes: -1
Reputation: 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
Upvotes: -1
Reputation: 6355
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)]))
Upvotes: -1
Reputation: 12156
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=', ')
Upvotes: 32
Reputation: 11927
Use
for i in range(n):
print(l[i], end=' ')
Or
print(*l, end=' ')
Upvotes: 4