I just wanted to know the use of the list() constructor because if we want to create a new list then just we can use square brackets, what's the specific use of the list() constructor.
newGrocerylist = list(("apple", "guava", "mango", "pineapple", "orange")) #Why use the list() constructor.
print(newGrocerylist)
#We can also do like this--
newGrocerylist = ["apple", "guava", "mango", "pineapple", "orange"]
print(newGrocerylist)
Answer
If you want to create a literal new list with a bunch of new values then you're right. There is no reason to use the list constructor, you should use the literal notation:
my_list = ['a', 'b', 'c']
In fact, it is impossible to create a new list with a bunch of values using the constructor, you can only use it to transform iterables into their list representation:
my_tuple = ('a', 'b', 'c') # literal notation to create a new tuple
my_list = list(my_tuple) # this is what you actually did in your first example
You can use the other iterable constructors like set
and dict
in a similar way. They are not used to create new objects, but transform existing ones into the type they describe.
No comments:
Post a Comment