+ 1

What is the difference between list(object) and [object]?

Do both produces same type of python list?

15th Jun 2020, 6:13 AM
Tricker
2 Answers
+ 3
Both ways do create the very same type of list - which is the typical Python list you know. If you write x = [] or x = list(), both times x will refer to a freshly created empty list, no difference. When you write list(whatever), you are calling the constructor of the type list. The argument you pass - if you pass anything - has to be an iterable type: so another list, a tuple, string, dictionary... Writing list(iterable) translated means: 'Please create a list out of the elements of iterable.' If you write x = [iterable], a different thing happens: iterable is not unpacked but will be put into a new list whole - as one single item. If you write [*iterable], unpacking that list with the *, then the result is really the same as list(iterable). Anyway, fundamentally, both a list call and a list literal (like []) will create the same sort of list.
15th Jun 2020, 7:48 AM
HonFu
HonFu - avatar
+ 3
The following snippet may hint a slight difference. str1 = "SoloLearn" tuple1 = (10, 20, 30, 40, 50) list1 = [10.1, 20.2, 30.3, 40.4, 50.5] print(f"Using string '{str1}'") print("list(str1) ->", list(str1)) print("[str1] ->", [str1]) print(f"\nUsing a tuple {tuple1}") print("list(tuple1) ->", list(tuple1)) print("[tuple1] ->", [tuple1]) print(f"\nUsing a list {list1}") print("list(list1) ->", list(list1)) print("[list1 ->]", [list1])
15th Jun 2020, 6:32 AM
Ipang