a couple of things I don't understand wrt lists

aaB mecagonoisician at gmail.com
Thu Apr 18 09:01:01 EDT 2013


Hello,

I am still in the process of writing preliminary code for my CA project.
I am now running into a behavior that I can't explain.

Here is a script which, at least on my system, shows the issue (python2.7 on a
linux system).
The final project will be wrapping these functions (and others) into a class
which will be in a module which can be imported into a script.

#!/usr/bin/python2

import sys
import random

def get_rule(rulenum):
  bitpattern = bin(rulenum)[2:]
  return [0]*(8-len(bitpattern)) + [int(bit) for bit in bitpattern]

def populate(n):
  random.seed()
  return [random.randint(0,1) for i in range(n)]

def get_index(thisgen, i):
  n = len(thisgen)-1
  cell = thisgen[i]
  if i is 0:
    print "i==0"
    prev, next = thisgen[n], thisgen[i+1]
  elif i is n:
    print "i==%d" % n
    prev, next = thisgen[i-1], thisgen[0]
  else:
    prev, next = thisgen[i-1], thisgen[i+1]
  return prev*4 + cell*2 + next

def get_nextgen(thisgen, rule):
  return [rule[get_index(thisgen, i)] for i in range(len(thisgen))]


if len(sys.argv) == 2:
  n = int(sys.argv[1])
else:
  n = 257

rule = get_rule(145)
thisgen = populate(n)
nextgen = get_nextgen(thisgen, rule)
print "done for n == 257"

n = 258
thisgen = populate(n)
nextgen = get_nextgen(thisgen, rule)


My issue is that when n == 257, the script runs as expected, but if n >= 258, I
get an "IndexError: list index out of range".
The script is also attached to the email in case someone would like to try it on
their machine.
The print statements in the get_index() function's branching show me that, when I
get the "out of range" error, the program doesn't enter the "elif i is n"
condition, although it does for lower values of n.
I'm sorry, but I still haven't found a way to copy/paste from the terminal to
vim.
This behaviour occurred previously and had stopped when I used an other version
of the get_index() function. At that time, get_index() wasn't a function and was
just conditional branching inside get_nextgen, I wanted to use the list
comprehension syntax to build nextgen, and this got me into seperating the
get_index() routine. 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: testca.py
Type: text/x-python
Size: 896 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20130418/baf78492/attachment.py>


More information about the Python-list mailing list