0

The first one is this:

n = int(input())
a = []
for i in range(n):
    a.append(int(input()))

The second one is this:

n = int(input())
a = [0]*n
for i in range(n):
    a[i] = int(input())

I have always been using first one, but the second one just came up to my mind. I don't know how append works, but I thought the second one could be more efficient than the first one.

Can I get answer of this problem?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dbld
  • 998
  • 1
  • 7
  • 17
  • If you can help it, get all the inputs in a single line separated by spaces or commas, and then split and convert to integer to create the list you are looking for. – recentadvances Nov 08 '20 at 02:37
  • 3
    Does this answer your question? [Python - Create a list with initial capacity](https://stackoverflow.com/questions/311775/python-create-a-list-with-initial-capacity) Per the accepted answer, "Conclusion: [preallocating the list] barely matters. Premature optimization is the root of all evil." – Brian61354270 Nov 08 '20 at 02:38
  • @Brian It does answer. Thanks for your comment – dbld Nov 08 '20 at 02:44

1 Answers1

1

I believe there should not be a definitive answer as it will depend on which version of Python, which platform, etc.

But in general, this is what you want to do to test it out real quick:

Create a file, say, testcode.py and make this:

def first():
    n = 100000
    a = []
    for i in range(n):
        a.append(int("42"))

def second():
    n = 100000
    a = [0]*n
    for i in range(n):
        a[i] = int("42")

Then run with timeit:

$ python -m timeit -s 'from testcode import first, second' -- 'first()'
10 loops, best of 5: 27.1 msec per loop
$ python -m timeit -s 'from testcode import first, second' -- 'second()'
10 loops, best of 5: 23.6 msec per loop
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
adrtam
  • 6,991
  • 2
  • 12
  • 27