-2

I am trying to generate random numbers and put them into a set. I decided to do it using for loop and range function:

for x in range(0, 21, 1):
    print(x)

Now I would like to put all the numbers into a set. I am using following code:

x_set = set(str((x)))
print(x_set)

Unfortunately the outcome is:

{'0', '2'}

I would like to put all numbers into a set (1 - 20). What am I doing wrong?

I am not looking for ready answers. Please show me the way to follow.

gosuto
  • 5,422
  • 6
  • 36
  • 57
piotrektnw
  • 120
  • 7
  • You just add the last nulber `20` that have been splitted in 0 and 2 with the `set` constructor, Use the `add` method in the loop, look the link in comment i've put – azro Apr 03 '20 at 18:45
  • could you please format the code correctly? Are these lines `x_set = set(str((x)))` etc. inside the loop? – norok2 Apr 03 '20 at 18:46
  • `set(range(21))` will create a list from [0,21) and convert it to a set – Chrispresso Apr 03 '20 at 18:48
  • 2
    `set(range(21))` – Jab Apr 03 '20 at 18:50
  • @Chrispresso Note that `set` takes any iterable, so there is no need to construct an intermediate list. `set(range(21))` will do. – Brian61354270 Apr 03 '20 at 18:50

1 Answers1

0

You are printing the numbers, you have to do something like:

x_set = set()
for x in range(0, 21, 1):
    x_set.add(x)
Bruno Mello
  • 4,448
  • 1
  • 9
  • 39