Testing Deque insert vs list insert methods using Datetime

Viewed 40

Short story: This question is about whether deque insert method is more efficient than the list insert method for inserting into positions other than the front and back of the arrays.

Long story: I had a task to produce a function that takes a list of 10 single int values and returns a string in the US phone number style, so I produced this basic function:

def create_phone_number(n):
    n.insert(0, '(')
    n.insert(4, ')')
    n.insert(5, ' ')
    n.insert(9, '-')
    n = ''.join([str(i) for i in n])
    return(n)

which turns [1,2,3,4,5,6,7,8,9,0] --> "(123) 456-7890". Perfect! However...

In my quest to learn more about efficiency in code I read that deque appendleft() method is faster than list insert(0, val) method. I wanted to test to see if this was also the case when inserting into any position other than the first and last positions of these arrays (since I couldn't find a definite answer to this).

To keep it relevant to my function, this was my test:

from collections import deque
from datetime import datetime
num = [1,2,3,4,5,6,7,8,9,0]

def create_phone_number(n):
    # Function using lists with 4 inserts repeated 10'000 times
    for x in range(10000):
        n.insert(0, '(')
        n.insert(4, ')')
        n.insert(5, ' ')
        n.insert(9, '-')
    n = ''.join([str(i) for i in n])
    return(n)

def create_phone_number2(n):
    # Function using deque with 4 inserts repeated 10'000 times
    d = deque(n)
    for x in range(10000):
        d.insert(0, '(')
        d.insert(4, ')')
        d.insert(5, ' ')
        d.insert(9, '-')
    n = ''.join([str(i) for i in d])
    return(n)


print('For list: ')
for i in range(5):
    start = datetime.now()
    create_phone_number(num)
    run = (datetime.now()-start)
    print(run)

print()

print('For deque: ')
for i in range(5):
    start = datetime.now()
    create_phone_number2(num)
    run = datetime.now()-start
    print(run)

Output:

For list: 
0:00:00.292415
0:00:00.866732
0:00:01.415827
0:00:01.983852
0:00:02.540520

For deque: 
0:00:00.031248
0:00:00.046866
0:00:00.031263
0:00:00.031247
0:00:00.031251

So as someone who is still learning Python and code efficiency, is deque insert method all round better than list insert for all positional inserts? And is my test using datetime adequate enough to support this conclusion? Any help is appreciated. Thanks

EDIT:

For the sake of completeness, I have found (what I believe to be) the ideal function to the problem nested at the heart of the question:

def create_phone_number(num): 
    return "({}{}{}) {}{}{}-{}{}{}{}".format(*num)
0 Answers
Related