Showing posts with label nested list. Show all posts
Showing posts with label nested list. Show all posts

Saturday, March 9, 2013

Python Nested List

In a previous post, I outlined a python function for creating nested lists. In retrospect, it was a naive, if functional, first attempt. As the size of the various dimensions increases, the function would become quite slow largely as a result of the deepcopy calls and recursion. A more efficient method would use the following syntax:

nestedList = [[[baseValue for x in range(axisLength)] 
                for y in range(axisLength)] for z in ...]

Now, a naive attempt to turn this into a function might do something like the following:

def nestedList(axisLength, degree, base):
  for x in range(degree):
    base = [base for y in range(axisLength)]
  return base

But this will actually just create shallow copies. The problem is that base is not recreated at each iteration. However, this is fixable with generators. For example:

def baseGen(base, axisLength):   
  while True:
    try: 
      yield [base.next() for x in range(axisLength)]
    except AttributeError:
      yield [base for x in range(axisLength)]

def nestedList(base, axisLength, degree):
  for d in range(degree):
    base = baseGen(base, axisLength)
  return base

Then, you would just call nList = nestedList(None, 5, 3) and then ls = nList.next() for a 5x5x5 cube with None as the base value. An added advantage of using generators is that you can just keep calling nList.next() every time you want a new cube.

Thursday, August 2, 2012

A Python Deep Copy Nested List Auto-Generator

An improvement on this notion is listed here.

I was trying to find a way to auto-generate a nested list with filler data that does not result in shallow copying problems (i.e., when I change one value, a whole bunch of values change). This is what I figured out using list comprehensions. Hence, it should be quite efficient. Error checking could be built-in but I didn't feel the need.


#builds a nested list from the inner-most list to the outer-most 
#listRangeTuples: must be a list or tuple of tuples to fill the 
#                 range values 
#degree: number of degrees or levels of nesting 
#theList: this is the variable that passes the lower nest at 
#         each point; it also sets the default value

import copy

def nestedListBuilder(listRangeTuples, degree=3, theList=None): 
    if degree == 0: 
        return theList 
    x = [copy.deepcopy(theList) for i in range    \
            (listRangeTuples[0][0], listRangeTuples[0][1])]
    return nestedListBuilder(listRangeTuples[1:], degree-1, x)