Feb 5, 2019

Compare List Vs List Comprehension, timeit

import timeit

# timeit.timeit(stmt, setup, timer, number)
# stmt   - which is the statement you want to measure it defaults to 'pass'.
# setup  - which is the code that you run before running the stmt; it defaults to 'pass'. We generally use this to import the required modules for our code.
# number - number of executions you like to run the stmt.

# List Comprehension
lst = [3, 2, 41, 3, 34, 99]
print(lst)

# If Condition alone - keep after the For loop
print([number for number in lst if number % 2 != 0])

# If-Else Condition - keep before For loop
print([number if number % 2 != 0 else -1 for number in lst])


#List Vs List Comprehension
#Ref: https://stackoverflow.com/questions/16341775/what-is-the-advantage-of-a-list-comprehension-over-a-for-loop
#List comprehensions are more compact and faster than an explicit for loop building a list:
#This is because calling .append() on a list causes the list object to grow (in chunks) to make space for new elements individually, while the list comprehension gathers all elements first before creating the list to fit the elements in one go:

def for_loop_test():
    result = []
    for elem in iter_var:
        result.append(elem)
    return result

def list_comprehension_test():
    return [elem for elem in iter_var]

if __name__ == '__main__':
iter_var = range(1000)
print timeit.timeit('f()', 'from __main__ import for_loop_test as f', number=10000)
print timeit.timeit('f()', 'from __main__ import list_comprehension_test as f', number=10000)


"""
Output:
1.41242463295
0.474811508482
"""'



No comments:

Post a Comment