Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating Lists within lists in python

I'm having trouble wrapping my head around dealing with lists within lists in python (I am rather new at programming).

Now how would I access each nested list position and then manipulate the position of the nested list's values to, for example, change their order while maintaining the position of the nested list in the main list.

For example: if I wanted to go from:

aList = [
    [1,2,3,4,3,2],
    [2,3,4,5,4,3],
    [2,1,2,3,4,3]
]

to here:

new_aList = [
     [2,3,4,3,2,1],
     [3,4,5,4,3,2],
     [3,4,3,2,1,2]
]

I get how to access each list, but I'm experiencing a block as to how I would change the position of the values of the nested lists.

Thanks for any help!

like image 340
Chris Avatar asked Dec 04 '22 19:12

Chris


2 Answers

Use a list comprehension to get the new elements, and optionally slice-assign to replace the existing elements in the list.

new_aList = [list(reversed(x)) for x in aList]
aList[:] = [list(reversed(x)) for x in aList]
like image 181
Ignacio Vazquez-Abrams Avatar answered Dec 24 '22 08:12

Ignacio Vazquez-Abrams


You could reverse each item like this

>>> aList = [
...     [1,2,3,4,3,2],
...     [2,3,4,5,4,3],
...     [2,1,2,3,4,3]
... ]
>>> aList[0].reverse()
>>> aList[1].reverse()
>>> aList[2].reverse()
>>> aList
[[2, 3, 4, 3, 2, 1], [3, 4, 5, 4, 3, 2], [3, 4, 3, 2, 1, 2]]

But in general it's better to use a loop since aList could have lots of items

>>> aList = [
...     [1,2,3,4,3,2],
...     [2,3,4,5,4,3],
...     [2,1,2,3,4,3]
... ]
>>> for item in aList:
...     item.reverse()
... 
>>> aList
[[2, 3, 4, 3, 2, 1], [3, 4, 5, 4, 3, 2], [3, 4, 3, 2, 1, 2]]

Both of those methods will modify aList in place, so the unmodified version is destroyed. Heres how you could create a new list and leave aList unchanged

>>> aList = [
...     [1,2,3,4,3,2],
...     [2,3,4,5,4,3],
...     [2,1,2,3,4,3]
... ]
>>> new_aList = []
>>> for item in aList:
...     new_aList.append(list(reversed(item)))
... 
>>> new_aList
[[2, 3, 4, 3, 2, 1], [3, 4, 5, 4, 3, 2], [3, 4, 3, 2, 1, 2]]

another way to reverse a list is to use this extended slice trick. The -1 means step through the list in steps of -1 ie. backwards.

>>> new_aList = []
>>> for item in aList:
...     new_aList.append(item[::-1])
... 
>>> new_aList
[[2, 3, 4, 3, 2, 1], [3, 4, 5, 4, 3, 2], [3, 4, 3, 2, 1, 2]]

Instead of explicitly making an empty list and appending to it, it is more usual to write a loop like this as a list comprehension

>>> new_aList = [item[::-1] for item in aList]
>>> new_aList
[[2, 3, 4, 3, 2, 1], [3, 4, 5, 4, 3, 2], [3, 4, 3, 2, 1, 2]]
like image 38
John La Rooy Avatar answered Dec 24 '22 08:12

John La Rooy