Is there any difference between checking whether ['a','b','c'] == ['a','b','c'] and 'abc' =='abc' ?
I don't expect there to be, but wanted to double check.
Is there any difference between checking whether ['a','b','c'] == ['a','b','c'] and 'abc' =='abc' ?
I don't expect there to be, but wanted to double check.
Below is a time test that uses timeit.timeit to compare the speeds of the two methods:
>>> from timeit import timeit
>>> list1 = ['a','b','c']
>>> list2 = ['x','y','z']
>>> timeit("list1 == list2", "from __main__ import list1, list2")
0.31944255484984296
>>> str1 = "abc"
>>> str2 = "xyz"
>>> timeit("str1 == str2", "from __main__ import str1, str2")
0.2439259738318924
>>>
As you can see, comparing two strings is somewhat faster than comparing two lists. For the reason why, see @user2864740's comment. :)
str1 and str2 refer to the same interned str object, so an equality test would be very fast: any object should compare equal to itself.s = 'abcdefghijklmnopqrstuvwxyz'* 18000 I measure 58.8ns to compare with itself and 1.29ms to compare two lists of the same content... a difference of 22000x!It appears that the string advantage increases as the sequences grow larger:
from timeit import timeit
for p in range(4):
N = 10 ** p
list1 = list(range(10)) * N
list2 = list(list1)
list2[-1] = 0
str1 = ''.join(map(str, list1))
str2 = ''.join(map(str, list2))
# Sequences are equal except for their last element.
# And everything is the same length.
assert list1[:-1] == list2[:-1]
assert str1[:-1] == str2[:-1]
assert list1 != list2
assert str1 != str2
assert len(list1) == len(list2)
assert len(str1) == len(str2)
assert len(list1) == len(str1)
a = timeit("list1 == list2", "from __main__ import list1, list2")
b = timeit("str1 == str2", "from __main__ import str1, str2")
print 'Length:', N * 10
print ' list: ', a
print ' str: ', b
print ' ratio: ', a / b
Some results:
Length: 10
list: 0.0885802666801
str: 0.0493016279308
ratio: 1.79670064454
Length: 100
list: 0.33228903865
str: 0.0540730467332
ratio: 6.14518801372
Length: 1000
list: 2.78192754261
str: 0.122594386356
ratio: 22.6921282882
Length: 10000
list: 26.8981546711
str: 0.78435279802
ratio: 34.2934387931