Type mismatchings and the rank newbie

Jeremy Hylton jeremy at alum.mit.edu
Fri Mar 16 17:33:25 EST 2001


>>>>> "JB" == John Brawley <jgbrawley at earthlink.net> writes:

  JB> Rank newbie here, trying to do something specific.  I need to
  JB> use a set of numbers (say, 1 to 25), and create 25 lists from
  JB> the numbers (1 thru 25), which lists have a character "P" and a
  JB> number (one of the 25).

  JB> The lists I want look like : 
      P1=[x, y, z] 
      P2=[x, y, z] 
      P3=[x, y, z] 
      (etcetera down to P25)

[...]

  JB> I need to write a loop that takes each number in sequence and
  JB> sticks it next to the ascii "P" so that when the loop is
  JB> finished, I end up with a set of lists each of whose names is
  JB> different by one number.

  JB> The loop is not a problem; I just can't figure how to stick a
  JB> different number form the user input total, into the second
  JB> place of the list name ( Pn=[x, y, z] where 'n' is the number
  JB> stuck in there by the loop) with every iteration of the loop.

  JB> The docs are confusing to me (I'm not a programmer and don't
  JB> want to be, but there is no other way for me to do what I need
  JB> to to see what this program will display for me).

  JB> Can anyone suggest a way out of this hole?

The point you're stuck at is: You have an integer, say, 12, and you
want to make an assignment to the name P12.  Is that right?

If so, then you need some a helper object that can direct you from the
number 12 to the variable P12.  There is no good way to invent the
variable name on the fly.  (It is technically possible using exec, but
this is fairly complicated and can be hard to understand.)

Is it absolutely necessary to use variables names P1, P2, etc?  It
would be simpler to use a dictionary.

    P = {}
    P[1] = [x, y, z]
    P[2] = [x, y, z]

If that's not possible, here is another, slightly more subtle
suggestion. 

    # These are place holders for the real values, which will be
    # created based on user input.
    P1 = []
    P2 = []
    ...
    P25 = []

    Plist = [P1, P2, P3, ..., P25]

    # get the user input here
    n = get_number()
    Plist[n].extend([x, y, z])
    # then Plist[n] => "Pn" => [x, y, z]

The above code works using references to the lists.  In Python, names
create references to objects.  Lists are mutable objects.  When you
call the extend method on a list, it modifies the list in place and
adds the elements of its argument.

>>> l = []
>>> l.extend([1])
>>> l
[1]
>>> l.extend([2, 3])
>>> l
[1, 2, 3]

Then you can bind the same object to a new name or put it in a list.

>>> l2 = l
>>> l2
[1, 2, 3]
>>> l.append(4)
>>> l
[1, 2, 3, 4]
>>> l2
[1, 2, 3, 4]
>>> list_of_lists = [l]
>>> list_of_lists
[[1, 2, 3, 4]]
>>> list_of_lists[0].append(5)
>>> list_of_lists
[[1, 2, 3, 4, 5]]
>>> l
[1, 2, 3, 4, 5]

Hope this helps.

Jeremy





More information about the Python-list mailing list