Paul
Paul

Reputation: 107

How to dynamically create new lists and store data into them

I want 4 new lists to be created (without me having to hardcode them in) with the names: page1, page2, page3, and page4. The number of outputted lists could change depending on the length of the initial list named: Numbers. I basically want to take each item in the list z, and store it into a list of its own (but the amount of items in z could change).

Numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
z = []
x = 0
w = 1
while (4*x) < len(Numbers):
    y = Numbers[0+(4*x):4 * w]
    z.insert(0,y)
    x += 1
    w += 1
print(list(reversed(z))) 
# [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]  *This is the output*

for items in z:
    # I don't know what to put here
    pass

# This is what I want my result to be 
# page1 = [1,2,3,4]
# page2 = [5,6,7,8]
# page3 = [9,10,11,12]
# page4 = [13,14,15,16]

^^This is what I want my final result to be^^

Upvotes: 0

Views: 53

Answers (3)

Andrew Jaffe
Andrew Jaffe

Reputation: 27077

Actually, your list z already does (almost) what you want:

  • z[0] is [1,2,3,4]
  • z[1] is [5,6,7,8]
  • etc.

You could also rename it:

page = z

which gives you page[0], page[1], etc.

So if you are willing to live with subscripts [...] and starting from zero instead of one, you're done.

(You could also be un-pythonic and do page = [[]] + z which would put an empty dummy entry into page[0] and then you could even start from page[1] for your real information.)

Upvotes: 0

jkobject
jkobject

Reputation: 69

Maybe a more pythonic way would be:

In [1]: pages = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

In [2]: listdict = {'pages'+str(i): val for i, val in enumerate(pages)}

In [3]: listdict
Out[3]: {'pages2': [9, 10, 11, 12], 'pages3': [13, 14, 15, 16], 'pages0': [1, 2, 3, 4], 'pages1': [5, 6, 7, 8]}

A dict is a nice data structure for this kind of usecases.

It also allows for better tracking of your data

Upvotes: 0

scnerd
scnerd

Reputation: 6103

You probably don't want a dynamically defined variable name, how would you refer to it later? What's wrong with keeping the list of lists around, and just indexing it?

Anyway, you can generate and run dynamic python code, so you could do something like the following:

In [1]: pages = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

In [2]: for i in range(len(pages)):
   ...:     exec(f'page{i + 1} = pages[{i}]')
   ...:

In [3]: page1
Out[3]: [1, 2, 3, 4]

if you want page1 to be a reference to pages[0] and not a copy of it, else:

In [4]: for i, lst in enumerate(pages):
   ...:     exec(f'page{i + 1} = {lst}')
   ...:

In [5]: page2
Out[5]: [5, 6, 7, 8]

which makes a copy of it, ONLY BECAUSE the printed form a list of literals, in Python, is itself a valid Python list literal. Don't try that if your inner lists contain objects or anything fancy.

Upvotes: 1

Related Questions