0

So just a simple Python list,

lst = []
for i in range(1000):
    lst.append(i)

# do they have the same time cost?
a = lst[100]
b = lst[-100]
J.R.
  • 769
  • 2
  • 10
  • 25
  • 3
    Does this answer your question? [Python List Indexing Efficiency](https://stackoverflow.com/questions/11400163/python-list-indexing-efficiency) – lorenzozane Nov 13 '20 at 11:27
  • 1
    @LorenzoZane thnx! That's actually a better version of my original question – J.R. Nov 13 '20 at 14:32

1 Answers1

0

Seems to be almost equivalent

import timeit

lst = []
for i in range(1000):
    lst.append(i)

# do they have the same time cost?

def a():
    return lst[100]


def b():
    return lst[-100]


if __name__ == '__main__':
    print(timeit.timeit("scr.a()", "import scr", number=100000))
    print(timeit.timeit("scr.b()", "import scr", number=100000))

>> 0.015244059000000004
>> 0.015558184000000003

Or with more iterations

>> 1.140082896
>> 1.1147582200000001

Which I would take to mean that they are as efficient as each other.

Daniel Lee
  • 7,189
  • 2
  • 26
  • 44