Difference between list () and [] in Python

Postscript

2019/12/11 postscript: In the comment, you pointed out an error in time measurement. We are currently revalidating with the correct code.

TL;DR --[] notation is more advantageous in execution time --Note that the handling of tuples is partially different between list () and [].

Motivation

Python has the philosophy There should be one--and preferably only one --obvious way to do it., but there are two ways to write a list, which is one of the most frequently used data structures. Is it against this philosophy? Is there any difference that allows for different definitions? I was worried.

I looked it up

StackOverflow had a similar question in 2015.

One's a function call, and one's a literal:

Well, list () is a function and [] is a literal. Well I do not know.

For the sake of completion, another thing to note is that list((a,b,c)) will return [a,b,c], whereas [(a,b,c)] will not unpack the tuple. This can be useful when you want to convert a tuple to a list. The reverse works too, tuple([a,b,c]) returns (a,b,c).

Indeed, the behavior for tuples is different. Does this difference in behavior show that the above function and literal are?

Quora also had a similar question in 2016.

The end result is the same whether you use [ ] or list() and same for { } vs. dict(). There is a difference in performance, though. [ ] and { } are more performant than the alternatives, list() and dict(), mainly because using list() and dict() involves the overhead of symbol lookup and function invocation.

In my opinion, using [ ] and { } is more pythonic. In addition, this notation allows you to take advantage of list/dictionary comprehension.

By the way, even in the dictionary type, there are two ways to define it with dict () and {}. Is the literal notation more Pythonic (like Python)? I still don't understand Python at all.

Verification

I found that some of them behave differently, but which one should be used in situations where they behave in the same way? Since there is a difference in the call between the function and the literal, I tried to verify it with the code that creates the object 100 times each.

Execution environment

Comparison of execution time

list.py


#-*- using:utf-8 -*-
import time

if __name__ == '__main__':
    start = time.time()
    
    for i in range(0,100):
        exec("list_%d = %s" % (i, []))
    elapsed_time1 = time.time() - start
    print ("elapsed_time:{0}".format(elapsed_time1) + "[sec]")

    start = time.time()

    for j in range(100,200):
        exec("list_%d = %s" % (j, list()))
    elapsed_time2 = time.time() - start
    print ("elapsed_time:{0}".format(elapsed_time2) + "[sec]")

~~ I see, there is a significant difference in execution time! By the way, the significance of the execution time in the literal [] was also recognized when the number of loops was set to 1000 and 10000. ~~

Treatment of tuples

As mentioned above, if you take a tuple as an argument at the time of generation, each will behave differently, What happens to the behavior after creating an object?

python


>>> l1 = []
>>> l1.append((1,2,3))
>>> print(l1)
[(1, 2, 3)]

>>> l2 = list()
>>> l2.append((1,2,3))
>>> print(l2)
[(1, 2, 3)]

There seems to be no difference in behavior once it is created as a list object. I think this area is Python or object-oriented ... I don't understand object-oriented.

List comprehension

Q. Can it be done? Can not? A. Either notation can be executed.

Recommended Posts

Difference between list () and [] in Python
Difference between append and + = in Python list
Difference between == and is in python
difference between statements (statements) and expressions (expressions) in Python
Difference between @classmethod and @staticmethod in Python
Difference between nonlocal and global in Python
[Python Iroha] Difference between List and Tuple
List concatenation method in python, difference between list.extend () and β€œ+” operator
[python] Difference between variables and self. Variables in class
About the difference between "==" and "is" in python
Difference between Ruby and Python split
Difference between java and python (memo)
Difference between Ruby and Python in terms of variables
Difference between python2 series and python3 series dict.keys ()
Difference between return, return None, and no return description in Python
[Python] Difference between function and method
Python --Difference between exec and eval
[Python] Difference between randrange () and randint ()
[Python] Difference between sorted and sorted (Colaboratory)
Python module num2words Difference in behavior between English and Russian
Differences in authenticity between Python and JavaScript
Differences between Ruby and Python in scope
Differences in syntax between Python and Java
Difference between PHP and Python finally and exit
[Python] Difference between class method and static method
[python] Difference between rand and randn output
Differences in multithreading between Python and Jython
Difference between numpy.ndarray and list (dimension, size)
Sorted list in Python
Filter List in Python
List find in Python
Difference in how to write if statement between ruby ​​and python
Transcendental simple and clear! !! Difference between single quotes and double quotes in Python
File open function in Python3 (difference between open and codecs.open and speed comparison)
[Introduction to Python] What is the difference between a list and a tuple?
Difference between process and job
Difference between "categorical_crossentropy" and "sparse_categorical_crossentropy"
Find the difference in Python
Difference between regression and classification
Stack and Queue in Python
Python list and tuples and commas
Python list comprehensions and generators
Difference between np.array and np.arange
Difference between MicroPython and CPython
Unittest and CI in Python
Getting list elements in Python
Difference between ps a and ps -a
Difference between return and print-Python
Implemented List and Bool in Python and SQLite3 (personal note)
[python] Calculation of months and years of difference in datetime
[Python] How to sort dict in list and instance in list
Mutual conversion between JSON and YAML / TOML in Python
Compare "relationship between log and infinity" in Gauche (0.9.4) and Python (3.5.1)
Difference in writing method to read external source code between Ruby and Python
Extract multiple list duplicates in Python
MIDI packages in Python midi and pretty_midi
[python] Manage functions in a list
Difference between SQLAlchemy filter () and filter_by ()
Output 2017 Premium Friday list in Python
View photos in Python and html
Sorting algorithm and implementation in Python