What you do can be easily done on one line with reversed and zip . The actual problem is in your code below in this answer.
Example -
list(zip(*reversed(yourlist)))
You don't need list(...) for Python 2.x, since zip() returns a list in Python 2.x.
Demo -
>>> list(zip(*reversed([[1,2,3], [4,5,6], [7,8,9]]))) [(7, 4, 1), (8, 5, 2), (9, 6, 3)] >>> list(zip(*reversed([[1,2,3,4], [5,6,7,8], [9,10,11,12]]))) [(9, 5, 1), (10, 6, 2), (11, 7, 3), (12, 8, 4)]
If you need a list of lists, not a list of tuples, you can use list comprehension (or map(list, zip(*reversed(....))) ). Example -
[list(x) for x in zip(*reversed(yourlist))]
Demo -
>>> [list(x) for x in zip(*reversed([[1,2,3], [4,5,6], [7,8,9]]))] [[7, 4, 1], [8, 5, 2], [9, 6, 3]] >>> [list(x) for x in zip(*reversed([[1,2,3,4], [5,6,7,8], [9,10,11,12]]))] [[9, 5, 1], [10, 6, 2], [11, 7, 3], [12, 8, 4]]
* is the syntax for unpacking, so the list returned by reversed() is unpacked in zip() and passed as separate arguments.
The zip() function then combines the elements of each of its arguments in the corresponding index (like all first arguments together, all other arguments together, etc.). Therefore, we get the desired result.
The actual problem for the source code is due to the following line -
for i in (range(len(list1)+1)):
You loop to len(list1) + 1 , so in the end you are trying to access elements like list1[0][len(list1)] , but this does not exist in your case.
Assuming list1 sublist all will have the same number of elements, what you really need is len(list1[0]) . Example -
def rotate(list1): bigList = [] #create a list that we will append on to for i in (range(len(list1[0]))): #loop through the list looking at the indexes newList = [] for j in reversed(range(len(list1))): #reverse that list newList.append(list1[j][i]) bigList.append((newList)) #append the elements to the bigList reversed return bigList
Demo -
>>> def rotate(list1): ... bigList = [] #create a list that we will append on to ... for i in (range(len(list1[0]))): #loop through the list looking at the indexes ... newList = [] ... for j in reversed(range(len(list1))): #reverse that list ... newList.append(list1[j][i]) ... bigList.append((newList)) #append the elements to the bigList reversed ... return bigList ... >>> rotate([[1,2,3], [4,5,6], [7,8,9]]) [[7, 4, 1], [8, 5, 2], [9, 6, 3]] >>> rotate([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) [[9, 5, 1], [10, 6, 2], [11, 7, 3], [12, 8, 4]]