I'm trying to print min() and max() values from a list generated from list()
x = [list(range(1,11))]
print(min(x))
print(max(x))
That returns the raw list twice: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
But when i write
x = [1,2,3,4,5,6,7,8,9,10]
print(min(x))
print(max(x))
It returns the actual min and max values: 1 and 10
What am i missing?
x = [list(range(1,11))]
is making a list
of list
s; the list
constructor converts the range
to a list
, and the square brackets then declare another list
that contains that list
. It's like doing:
x = [[1,2,3,4,5,6,7,8,9,10]] # Note two brackets on each side
Obviously, the max
and min
of a list
with only one element (the inner list) will be that single element. It's the everything-est of elements in that list
. If you want it equivalent to:
x = [1,2,3,4,5,6,7,8,9,10]
just do:
x = list(range(1,11)) # No brackets needed; the list constructor makes a single unnested list
or if you really like the bracket syntax, you can use generalized unpacking like so:
x = [*range(1,11)] # * unpacks the range as elements of the list literal