-2

I have the following code:

 import numpy as np
 import math as mat

 list_of_numbers = {int(mat.sqrt(x)) for x in range(7)}

 print(list_of_numbers)

I was expecting the output to be the square root of each number from zero to 6.

i.e., [0, 1, 1, 1, 2, 2, 2]

Why is it that Python only prints

[0, 1, 2]

I have checked the documentation on print https://www.python-course.eu/python3_print.php

It seems that there is no reference about print not printing duplicate values. Can anyone help?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

3 Answers3

3

You have created a set literal here:

list_of_numbers = {int(mat.sqrt(x)) for x in range(7)}

Sets don't store duplicates. They're useful data structures for checking membership for things that can be hashed.

They are definitely not the same thing as lists.

To create a list, you just need to swap { and } for [ and ]:

 list_of_numbers = [int(mat.sqrt(x)) for x in range(7)]
erewok
  • 7,555
  • 3
  • 33
  • 45
2

It is because you are using a Set instead of a List. Try:

import numpy as np
import math as mat

list_of_numbers = [int(mat.sqrt(x)) for x in range(7)]

print(list_of_numbers)
Trevor Jex
  • 274
  • 2
  • 15
2

You need to change

list_of_numbers = {int(mat.sqrt(x)) for x in range(7)}

to

list_of_numbers = [int(mat.sqrt(x)) for x in range(7)]
Pang
  • 9,564
  • 146
  • 81
  • 122
user6606453
  • 69
  • 10