Educative

The example given is incorrect

You have given the example
print(list(range(1, 10, 2)))

This will return an error because list is not a callable data structure.

However the same has to be modified as
new_number=[]
for numbers in range(1,10,2):
print(numbers)
new_number.append(numbers)
print(new_number)

In regards to your concern, the ‘list()’ is a pre-defined constructor for <class ‘list’> in Python which takes a ‘range’ object as an argument. ‘‘range()” is also a constructor that returns a <class ‘range’> object, therefore it can be passed to list() constructor in order to get a ‘list’ object. The code that our example provides works fine and does not produce any error because of the above mentioned reason.

The alternate example that you provided also creates a list but it first creates an empty list and then adds each element iteratively using the ‘append()’ function. The ‘list’ constructor does the same but more concisely and efficiently. That is the reason we used the list constructor in this example instead of what you suggested, demonstrating its purpose.

I hope it clarifies!

Best Regards,
Aafaq Sabir | Developer Advocate
Educative

1 Like