strange append

James Stroud jstroud at mbi.ucla.edu
Mon Oct 2 15:53:57 EDT 2006


E.Nurminski wrote (off the  list):
> the intention was to have
> 
> newx = [1, 2]
> res = [[1, 2]]
> newx = [1, 3]
> res = [[1, 2], [1, 3]]
> newx = [1, 4]
> res = [[1, 2], [1, 3], [1, 4]]
> newx = [1, 5]
> res = [[1, 2], [1, 3], [1, 4], [1, 5]]
> newx = [1, 6]
> res = [[1, 2], [1, 3], [1, 4], [1, 5], [1, 6]]

This shows how valuable it is to post your expected results with your code.

The way most experienced python programmers might do this is with list 
comprehension:

res = [[1, i] for i in xrange(1,7)]

For newer programmers, this might make more sense:

res = []
for i in xrange(1,7):
   res.append([1,i])

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list