0

How Can i print only value of list in same line ? My Code is:

t = int(input())
for case_no in range(1, t+1):
    n = int(input())
    li = list()
    for i in range(1, n+1):
        if n % i == 0:
            li.append(i)
    print("Case {}: {}".format(case_no, li, sep=' ', end=''))

My Input Output Sample Result:

2
6
Case 1: [1, 2, 3, 6]
23
Case 2: [1, 23]

My Expected Output:

2
6
Case 1: 1 2 3 6
23
Case 2: 1 23
Sajib Hossain
  • 81
  • 1
  • 12

4 Answers4

1

Try join() to convert your list to string -

" ".join(map(str, li))

Here your list is a list of integers and join() joins every string element of an iterable separated by some string (in this case " "). So, you need to convert each integer to a string first. map() can do that. map() takes a function and apply it on each element of an iterable which is passes as the second arguement (here list li). So, map(str, li) will create an iterable where each element is a string representation of every element of list li

So, your line would be-

print("Case {}: {}".format(case_no, " ".join(map(str, li)), sep=' ', end=''))

You can use generator expression for that too -

print("Case {}: {}".format(case_no, " ".join(str(i) for i in li), sep=' ', end=''))

In this case you are using a generator expression (think of it like list comprehension if you don't know). The generator expresssion iterates over every element of li and returns a stringified (don't know if that's the word) version of that element.

Also, if you just want to print the list and not maintain it for other purposes then you can just simplify it a bit -

t = int(input())
for case_no in range(1, t+1):
    n = int(input())
    print("Case {}: {}".format(case_no, " ".join(str(i) for i in range(1, n+1) if not n % i), sep=' ', end=''))
kuro
  • 3,214
  • 3
  • 15
  • 31
0

You can use print to do it:

data = [[1,2,3,4], [2,4,6]]

for idx,d in enumerate(data,1):
    print( f"Case {idx}:", *d)  # "splat" the list 

prints:

Case 1: 1 2 3 4
Case 2: 2 4 6

Using the splat (*) (or unpacking argument lists) operator to provide all elements of your list as parameters to print:

print( *[1,2,3,4]) == print( 1, 2, 3, 4)
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

Either you make a string out of the list, either you need another loop to parse the list. There might be other solutions as well.

You can use a comma after the print statement to avoid adding new line.

Making a string :

  print("Case {}: {}".format(case_no, "".join(str(li).split(',')).strip('[]'), sep=' ', end=''))

With loop:

print("Case {}: ".format(case_no)),
for i in li:
    print(i),
print
magor
  • 670
  • 10
  • 14
0

You can make elements in list as string li.append(str(i)) And then have join " ".join(li)

Sakura
  • 1