#1
  1. PHP ninja
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Location
    Melbourne, Australia
    Posts
    20
    Rep Power
    0

    Creating a list of tuples


    I am trying to populate a list ot tuples on the fly from a file but keep running into these errors:
    Code:
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "forum.py", line 84, in getPosts
        posts[0] =  [(details[0],(details[1],details[2],details[3]),post)]
    IndexError: list assignment index out of range
    Here is and simplified example of what i am trying to do:
    Code:
     def getDetails(path, id):
        "Returns a list of user details in file "
        f = open(path + id + ".info", "r")
        index = 0
        posts = []
        line = f.readline()
        while line != "":
          line = f.readline()
          details = string.split(line[:-1], ",")
          posts[index] =  [(details[0],(details[1],details[2],details[3]),details[4])]
          index += 1
        f.close()
        return posts
    Can somebody help I seem to be stuck
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    Unlike some languages, Python does not automatically extend lists when you assign values past the end. You need to use the append method instead, i.e.

    Code:
    posts.append([(details[0],(details[1],details[2],details[3]),details[4])])
    BTW, if the original data is in CSV (comma separated variables) format then you could use the new csv module to parse it. This will correctly handle commas inside quoted strings.

    Dave - The Developers' Coach

IMN logo majestic logo threadwatch logo seochat tools logo