I’m looking for a way to do the following:
- I have a list composed of other lists:
TABLE=[table1,table2,table3] - I would like to duplicate this list but rename the sublists, such as:
TABLE_1=[table1_dup=list(table1),table2_dup=list(table2),table3_dup=list(table3)](this doesn’t work; I’m just trying to explain my goal) so that I can access tablex and tablex_dup independently after performing batch operations on the whole TABLE and TABLE_1, which include table1, table2, … and the duplicates.
Thanks a lot!
EDIT: The sublists aren’t necessarily named the same (table1, table2, table3). Actually, their names are quite different (e.g. up, down, left, right)
EDIT #2:
I’m kinda new to this. Basically, here’s my code:
up=["img1.png","img2.png"]
similar things for down, left and right.
table=[up,down,left,right]
Now using pygame:
for j in range(len(table)):
for i in range(len(table[j])):
table[j][i] = pygame.image.load(os.path.join(str(table[j][i])))
table_r[j][i] = pygame.image.load(os.path.join(str(table_r[j][i])))
table_r[j][i] = pygame.transform.flip(table_r[j][i],1,0)
This wouldn’t work as there is no up_r, for example, that I could access. Only up.
On the more general issues raised in the comments and by your edits – it seems very much like a list of lists isn’t the right data structure for your logic here. A list is usually indicated when you can have arbitrarily many ‘rows’ in your table – it seems you always have exactly four. A tuple is better in this case – it is kindof like a list, except it is set up more deliberately for things that don’t change. And, even better, since you want to address your four things by name, there’s a standard Python class called
collections.namedtuplethat makes this easy.You would define a Table class like this:
And then you create your first table like this:
This lets you get your ‘up’ list as
table.up, which means when you do a deepcopy intotable_rper Constantinius’ answer, these names come with it for free. And it also lets you iterate over it in exactly the same way as your list:However, note that iterating over
range(len(iterable))is usually not necessary – since you’re using the index to look up values from your two tables simultaneously, what you really want is a combination of the builtin functionsenumerateandzip:You only need the index to assign into the lists, since rebinding
valandval_rinside the inner loop won’t work. Since you don’t usejas anything other than a lookup, you don’t need it at all.But this also brings up the one caviat of using a namedtuple – the one thing it can’t do that you might care about is change an attribute of the tuple after it is created:
In your case, this means you can’t reassign
table.upto a new list at any point (you can still change the list itself, though, through its mutation methods and slice assignment) – if you need that, you’re best off coding your own class for this.