generating unique variable name via loops

Matthew Ruffalo mmr15 at case.edu
Tue Nov 4 10:04:18 EST 2014


Hi-

Questions like this appear so often in various places (mailing lists,
forums, sites like Stack Overflow) that I think a very blunt/candid
answer is appropriate. This is especially true since there's always
someone who responds to the question as-is with some monstrosity of
exec() and string formatting, instead of addressing the underlying issue
of using the right data structure for what you're trying to accomplish.

On 11/04/2014 06:29 AM, Fatih Güven wrote:
> I want to generate a unique variable name for list using python.
>
> list1=...
> list2=...
> .
> .
> .
> listx=... where x is a number.
*Incorrect.* You do not want to do this. You think you do, but that's
presumably because you aren't familiar with common data structures that
are available in Python. As Peter Otten said, this is *exactly* the
right situation to use a list.

You mentioned having structured and repetitive data, wanting to read a
.txt file and process each line, and wanting to access each employee's
data as appropriate. The general structure of this would be

>>> employees = []
>>> with open('employee_data.txt') as f:
...     for line in f:
...         # parse_line here isn't anything standard or built-in, it's
...         # what you would write to transform a line of the data
...         # file into whatever object you're interested in with
...         # 'name', 'salary', etc. attributes
...         employee = parse_line(line)
...         employees.append(employee)
...
>>> employees[0].salary
150000

Your line1 is now employees[0] and so on. Now, you can *easily* answer
questions like "what's the total salary of all employees?"

>>> total = 0
>>> for employee in employees:
...     total += employee.salary
...
>>> total
7502000

(or 'sum(employee.salary for employee in employees)' of course.)

MMR...




More information about the Python-list mailing list