the most efficient method of adding elements to the list

A

alf

Hi,

Would it be .append()? Does it reallocate te list with each apend?

l=[]
for i in xrange(n):
l.append(i)


Thx, A.
 
G

Girish Sahani

Hi,
Would it be .append()? Does it reallocate te list with each apend?
Yes it does.
If order of the new element being added doesnt matter you can use append.
If it does, you can use insert().
l=[]
for i in xrange(n):
l.append(i)


Thx, A.
 
E

Erik Max Francis

alf said:
Would it be .append()? Does it reallocate te list with each apend?

l=[]
for i in xrange(n):
l.append(i)

No, it doesn't. It expands the capacity of the list if necessary.
 
K

K.S.Sreeram

alf said:
Would it be .append()? Does it reallocate te list with each apend?

No append does NOT reallocate for every call. Whenever a reallocation
happens, the newsize is proportional to the older size. So you should
essentially get amortized constant time for every append call.

If you want to add a bunch of items in one call.. you should use the
'extend' method.

Regards
Sreeram


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFEhQlLrgn0plK5qqURApHbAKC1A2xYXdgyj9+4a4Nkg79+rMdfrwCgi4xP
4VMZi08TTCKblHBxMssZEYA=
=DdkB
-----END PGP SIGNATURE-----
 
B

bruno at modulix

alf said:
Hi,

Would it be .append()? Does it reallocate te list with each apend?

l=[]
for i in xrange(n):
l.append(i)

<dumb>
FWIW, you'd have the same result with:
l = range(n)
</dumb>


More seriously (and in addition to other anwsers): you can also
construct a list in one path:

l = [i for i in xrange(n)]

or if you want operations and conditionals :

l = [trasform(i) for i in xrange(n) if match_some_cond(i)]



HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top