1

Can Python automatically create a new array and append new information to it, within a loop? This is just a question for learning purposes.

For example, I am trying to write a program that appends information to an array called record001. Then after some steps, want to append new information to a new array, but create that variable name automatically within a loop? Is this possible? I've given an example below:

counter = 0
record001 = []
    while (counter > -1):

        user_id = input("Enter your 5-digit ID: ")
        record001.append(user_id)

        yob = int(input("Enter your 4-digit year of birth: "))
        record001.append(yob)

        counter += 1
            print("Information Appended to Record #: " + str(counter))
            print(record001)

else:
     print("Program terminated")

Thank you

Victor Rodriguez
  • 531
  • 1
  • 10
  • 18
  • possible duplicate of [How to increment variable names/Is this a bad idea](http://stackoverflow.com/questions/2488457/how-to-increment-variable-names-is-this-a-bad-idea) – Joel Sep 20 '15 at 15:06

2 Answers2

0

You can't easily do what you are asking, but you can have a two dimensional array of records, for example:

>>> records = []
>>> for i in range(10):
...     record = []
...     records.append(record)
...     record.append(i)
...     record.append(i ** 2)
... 
>>> records
[[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]
Patrick Maupin
  • 8,024
  • 2
  • 23
  • 42
0

Patrick's suggestion to use a multi-dimensional array works great for what I was trying to do. I assume that the overall answer to the theory part of my question- can a variable name itself be manipulated- is no.

Here is the program using a multi-dimensional array (as kindly suggested by Patrick)

counter = 0
records = []

while (counter > -1):
    record = []
    user_id = input("Enter your 5-digit ID: ")
    record.append(user_id)

    yob = int(input("Enter your 4-digit year of birth: "))
    record.append(yob)
    records.append(record)

    counter += 1
    print("Information Appended to Record #: " + str(counter))
    print(records)

else:
    print("Program terminated")
Victor Rodriguez
  • 531
  • 1
  • 10
  • 18
  • Glad you got it to work! You actually can manipulate variable names, because namespaces are simply dictionaries. So, for example, you could set a variable in the global name space by using `globals()['my_variable_name'] = new_value` but that's usually a lot of work for not much gain... – Patrick Maupin Sep 21 '15 at 17:04