- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Which is faster to initialize lists?
Python is a very flexible language where a single task can be performed in a number of ways, for example initializing lists can be performed in many ways. However, there are subtle differences in these seemingly similar methods. Python which is popular for its simplicity and readability is equally infamous for being slow compared to C++ or Java. The ‘for’ loop is especially known to be slow whereas methods like map() and filter() known to be faster because they are written in C.
# import time module to calculate times import time # initialise lists to save the times forLoopTime =  whileLoopTime =  listComprehensionTime =  starOperatorTime =  # repeat the process for 500 times # and calculate average of times taken. for k in range(500): # start time start = time.time() # declare empty list a =  # run a for loop for 10000 times for i in range(10000): a.append(0) # stop time stop = time.time() forLoopTime.append(stop-start) # start time start = time.time() # declare an empty list a =  i = 0 # run a for loop 10000 times while(i<10000): a.append(0) i+= 1 stop = time.time() whileLoopTime.append(stop-start) start = time.time() # list comprehension to initialize list a = [0 for i in range(10000)] stop = time.time() listComprehensionTime.append(stop-start) start = time.time() # using the * operator a = *10000 stop = time.time() starOperatorTime.append(stop-start) print("Average time taken by for loop: " + str(sum(forLoopTime)/100)) print("Average time taken by while loop: " + str(sum(whileLoopTime)/100)) print("Average time taken by list comprehensions: " + str(sum(listComprehensionTime)/100)) print("Average time taken by * operator: " + str(sum(starOperatorTime)/100))
Average time taken by for loop: 0.00623725175858 Average time taken by while loop: 0.00887670278549 Average time taken by list comprehensions: 0.00318484544754 Average time taken by * operator: 0.000371544361115
- Which is faster, NumPy or pandas?
- Which is faster between C++ and C#?
- Which one is faster Array or List in Java
- Which is faster? Constants, Variables or Variable Arrays in PHP?
- Which is faster, a MySQL CASE statement or a PHP if statement?
- What is correct syntax to create Python lists?
- How to make loops run faster using Python?
- Initialize Matrix in Python
- Python - Ways to initialize list with alphabets
- Initialize tuples with parameters in Python
- Updating Lists in Python
- Is SELECT * faster than 40 columns listing in MySQL?
- Why does Python code run faster in a function?