Be carefull when creating list in Python using bracket [] or list() method


There are big difference between list() and [] in Python. The first one for list() it will seeking iterable objects and make the object into list. The second one will be just wrap the object into list type.

The same object with same result:

1
2
3
4
a = list(1)
b = [1]
print(a)
print(b)


This code will produce :

1
2
[1]
[1]

And the other one is same object with different result:

1
2
3
4
5
text = "Hello World"
a = list(text)
b = [text]
print(a)
print(b)

It will gave result :

1
2
[‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
["Hello World"]

So, be carefull when we need to casting object or want to encapsulape it into list because it have different value.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.