0
import random
n=[random.randint(10,999) for i in range(int(input()))]

print(n,end=', ')

The problem is I need it to print without squared brackets. How can I change my code by not over complicating it.

Here is what it prints out:

[385, 396, 37, 835, 376],

and it needs to look like this

305, 396, 37, 835, 376

I have tried putting brackets in multiple places also I have tried deleting things and all that happens is it prints the same thing or there is error.

Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51
TurtleSam
  • 29
  • 5

3 Answers3

1

Convert the ints to strings and use join:

>>> n = [385, 396, 37, 835, 376]
>>> print(", ".join(map(str, n)))
385, 396, 37, 835, 376

Another option is to use the * operator to spread n as multiple arguments to print:

>>> print(*n, sep=", ")
385, 396, 37, 835, 376
Samwise
  • 68,105
  • 3
  • 30
  • 44
-1
>>> n = [385, 396, 37, 835, 376]
>>> print(str(n)[1:-1])

385, 396, 37, 835, 376
Rivered
  • 741
  • 7
  • 27
-2

You have a list of integers. You can convert them to strings and use the string.join method to get the format you want.

import random
n=[random.randint(10,999) for i in range(int(input()))]

print(", ".join(str(val) for val in n),end=', ')

(Note: map is an odd thing to use in a language that already has native mapping constructs. Best to keep it native).

tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • no matter whether I use a generator expression or `map` in an answer like this, someone always goes out of their way to complain that it wasn't the other one. I just flip a coin each time now. :) – Samwise Mar 30 '22 at 17:51
  • Why even construct a list when you can just use an iterator? `n=(random.randint(10,999) for i in range(int(input())))` – md2perpe Mar 31 '22 at 15:10
  • @md2perpe - Yes, you can do that too. My answer is focused on the display part. Given a list, how to print. In fact, it would work with many types of sequences or generators. For this exact script, your suggestion is very good. – tdelaney Mar 31 '22 at 16:23
  • @Samwise - true, but... map/filter/reduce are functional programming concepts. Although you can do functional programming with python, its not built that way top to bottom. Other functional programming tools are in `functools` and map/filter/reduce should be there also. Comprehensions are the "built in" way to do this. map's existance in `builtins` is a fluke. – tdelaney Mar 31 '22 at 16:42
  • Why the `end=','`? It will add an extra comma at the end... – Tomerikoo Mar 31 '22 at 18:20
  • @Tomerikoo - yes, it replaces the newline normally written... but that's what the original code does too. I don't know the poster's intent with that so I just left it. You could ask the author what the intent was. – tdelaney Mar 31 '22 at 21:44