Reputation: 7386
I noticed a strange difference between two list constructors that I believed to be equivalent.
Here is a small example:
hello = 'Hello World'
first = list(hello)
second = [hello]
print(first)
print(second)
This code will produce the following output:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
['Hello World']
So, the difference is quite clear between the two constructors... And, I guess that this could be generalized to other constructors as well, but I fail to understand the logic behind it.
Can somebody cast its lights upon my interrogations?
Upvotes: 1
Views: 256
Reputation: 3203
The most important distinction of these 2 behaviours comes when you work with generators. Given that Python 3 transformed things like map
and zip
into generators ...
If we assume map
returns generators:
a = list(map(lambda x: str(x), [1, 2, 3]))
print(a)
The result is:
['1', '2', '3']
But if we do:
a = [map(lambda x: str(x), [1, 2, 3])]
print(a)
The result is:
[<map object at 0x00000209231CB2E8>]
It is obvious that the 2nd case is in most situations undesirable and not expected.
P.S.
If you are in Python 2, then do at the beginning: from itertools import imap as map
Upvotes: 1
Reputation: 530960
You are assuming that list(hello)
should create a list containing one element, the object referred to by hello
. That's not true; by that logic you would expect list(5)
to return [5]
. list
takes a single iterable argument (a list, a tuple, a string, a dict, etc) and returns a list whose elements are taken from the given iterable.
The bracket notation, however, is not limited to containing a single item. Each comma-separated object is treated as a distinct element for the new list.
Upvotes: 1
Reputation: 3215
The first just transform the list "Hello world" (an character array) into a list
first = list(hello)
The second create a list with element inside brackets.
first = [hello]
In the second case for example you could also do:
first = [hello, 'hi', 'world']
and as output of the print you will get
['Hello World', 'hi', 'world']
Upvotes: 2
Reputation: 522016
The list()
constructor function takes exactly one argument, which must be an iterable. It returns a new list with each element being an element from the given iterable. Since strings are iterable (by character), a list with individual characters is returned.
[]
takes as many "arguments" as you like, each being a single element in the list; the items are not "evaluated" or iterated, they are taken as is.
Everything as documented.
Upvotes: 8
Reputation: 2424
your "first" uses the list method, which takes in hello and treats it as an iterable, converting it to a list. Which is why each chararcter is seperate.
your "second" creates a new list, using the string as its value
Upvotes: 1
Reputation: 947
first = list(hello)
converts a string into a list.
second = [hello]
this places an item into a new list. it is not a constructor
Upvotes: 0