Converting List of String to Integer

Andrew Freeman alif016 at gmail.com
Mon Jul 21 19:38:32 EDT 2008


Samir wrote:
> For my small list, I didn't notice a
> discernible increase in speed, but I may have to try it with a larger
> list size.
>   

About speed, and memory consumption:
List comprehensions 
(http://docs.python.org/tut/node7.html#SECTION007140000000000000000) are 
just shortcuts for for-loops. I do not believe there is any speed 
benefit. However, there are generators, they basically load one part of 
an iterator (a list in this case) at a time, this can greatly reduce 
memory usage.
Have a look at PEP 289:
http://www.python.org/dev/peps/pep-0289/

Here is the list comprehension as a generator (actually 2):
n = ((int(i) for i in k) for k in a)


Note, you can't just print a generator, it only computes something when 
needed:
 >>> print n
<generator object at 0xb7820e2c>

You can, however iterate over it:

In [2]: for k in n:
   ....:     for i in k:
   ....:         print i,
   ....:        
   ....:        
1 2 3 4 5 6 7 8 9 0
In [3]: n = ((int(i) for i in k) for k in a)
In [49]: list(n)
Out[49]:
[<generator object at 0xb77d03ec>,
 <generator object at 0xb77d03cc>,
 <generator object at 0xb77d046c>,
 <generator object at 0xb77d04ac>]

Each sub-list is a generator too!
In [50]: n = ((int(i) for i in k) for k in a)
In [51]: for i in list(n): # list() converts the variable n to a list
   ....:     list(i)
   ....:    
   ....:    
Out[51]: [1, 2]
Out[51]: [3]
Out[51]: [4, 5, 6]
Out[51]: [7, 8, 9, 0]


This is only going to make a difference if you were dealing with a 
*very* large data set. I thought I would show you even if you never user 
them, for learning purposes. Note: a generator is one way, redefine it 
every time you use it.
--
Andrew




More information about the Python-list mailing list