Creating a list with holes

Denis McMahon denismfmcmahon at gmail.com
Fri Jan 3 21:03:13 EST 2014


On Fri, 03 Jan 2014 20:18:06 -0500, Roy Smith wrote:

> In article <mailman.4871.1388794533.18130.python-list at python.org>,
>  Larry Martell <larry.martell at gmail.com> wrote:
> 
> 
>> Thanks, but I know all that about dicts. I need to use a list for
>> compatibility with existing code.
> 
> Generalizing what I think the situation is, "A dict is the best data
> structure for the parsing phase, but I need a list later to hand off to
> legacy interfaces".
> 
> No problem.  Parse the data using a dict, then convert the dict to a
> list later.  I haven't been following all the details here, but just
> wanted to point out that using different data structures to hold the
> same data at different phases of a program is a perfectly reasonable
> approach.

Indeed, assuming the requirement is to have a list of some length n units 
representing integer keys into a range of values from start to end, and 
he creates a dict initially:

list = [ dict.get(x,None) for x in range(start,end + 1) ]

Examples:

>>> dic = {1:"fred", 9:"jim", 15:"susan", 25:"albert" }
>>> l = [ dic.get(x,None) for x in range(1,20) ]
>>> l
['fred', None, None, None, None, None, None, None, 'jim', None, None, 
None, None, None, 'susan', None, None, None, None]
>>> l = [ dic.get(x,None) for x in range(-10,50) ]
>>> l
[None, None, None, None, None, None, None, None, None, None, None, 'fred', 
None, None, None, None, None, None, None, 'jim', None, None, None, None, 
None, 'susan', None, None, None, None, None, None, None, None, None, 
'albert', None, None, None, None, None, None, None, None, None, None, 
None, None, None, None, None, None, None, None, None, None, None, None, 
None, None]
>>> len(l)
60

then the value of l[offset] will either be None or some string depending 
on the offset into the list

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list