Get the previous item in a list of lists

advertisements

I have a list the_list = [[3, 2, 0, 1, 4, 5], [4, 2, 1, 3, 0, 5], [0, 1, 2, 3, 4, 5]].How do I print the previous element from any randomly chosen element in the three lists in the_list. If the randomly chosen element is at index 0, then the previous element would be the element at the end of the list. For example, if I pick rande = 3 for the list, then I will get the following output:

5
1
2

How do I code this in the whilst having the most efficient time complexity?


Use the list.index() method and take advantage of the fact that negative numbers index a list from the end:

>>> the_list = [[3, 2, 0, 1, 4, 5], [4, 2, 1, 3, 0, 5], [0, 1, 2, 3, 4, 5]]
>>> rande = 3
>>> for subl in the_list:
...     print(subl[subl.index(rande)-1])
...
5
1
2