Search code examples
listsquare-bracket

What are the differences between list() and square bracket in Python?


I get to put in some strings, and make it into list, each characters seperated.

some_string = input()

string_list = list(*some_string)
print(string_list)

but list doesn't get this argument if string length is greater than 2. instead, when I use square bracket, "[]", it works even if it is greater than 2.

some_string = input()

string_list = [*some_string]
print(string_list)

This means these two are different.

So I tried help(list()) and help([]) to find the difference between these two, but these two get the same help documentation written below.

Help on list object:


class list(object)
|  list(iterable=(), /)
|
|  Built-in mutable sequence.
|
|  If no argument is given, the constructor creates a new empty list.
|  The argument must be an iterable if specified.
|
|  Methods defined here:
\-- More --

If these two are the same, why is one working and why not the other?


Solution

  • For list() constructor, it accepts as single argument iterable object as argument, yes in above code snippet string is iterable (i.e variable: some_string). If we unpack the *some_string, it results out in many arguments to that constructor and it results out in error as list constructor accepts only an single argument

    please refer this link for detailed explanation about when to use list constructor in python, : https://www.pythonmorsels.com/using-list/

    some_string='World'
    some_list=list(some_string)
    print(some_list)