0

I have used the following code to merge 2 list items. For example, list 'c' is a creation of list variables 'a' and 'b'

a=[['2022', 4], ['2023', 5]]
b=["Random1","Random2"]
c=list(zip(a,b))

'c' therefore looks like this

Out[]: [(['2022', 4], 'Random1'), (['2023', 5], 'Random2')]

i tried to sort 'c' on the 2nd and 3rd column i.e.

c_sorted=c.sort(key=lambda i:(i[1],i[2]))

however i get the error IndexError: tuple index out of range

Any help would be greatly appreciated! thanks!

SeaTurtle
  • 11
  • 2
  • What third item? The first element of `c` is the two-element tuple `(['2022',4], 'Random1')`. The first element is the list `['2022',4]` and the second is the string `Random1`. What do you want to sort by? – Mark Reed Jun 18 '23 at 14:46

2 Answers2

1

You're not exactly getting 3 equal columns after the merge, but rather a tuple of a list and a plain value as you posted:

Out[]: [(['2022', 4], 'Random1'), (['2023', 5], 'Random2')]

You want to properly index on the columns and it should work:

>>> sorted(c, key=lambda i:(i[0][1], i[1]))
[(['2022', 4], 'Random1'), (['2023', 5], 'Random2')]

You might be tempted to attempt something like

key = lambda ((year, number), random_string): (number, random_string) 

but this was actually removed in PEP 3113

Alternatively you could truly merge the lists to the result you wanted with this list comprehension instead of the plain list call:

>>> [x + [y] for x, y in zip(a, b)]
[['2022', 4, 'Random1'], ['2023', 5, 'Random2']]

Now your initial code should work fine.

Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69
1

"IndexError: tuple index out of range," occurs because the elements in your list c are tuples, and you are trying to access the second and third indices of each tuple. However, the tuples in c have only two elements: the first element from a and the corresponding element from b. corrected answer can be:

a = [['2022', 4], ['2023', 5]]
b = ["Random1", "Random2"]
c = list(zip(a, b))

c_sorted = sorted(c, key=lambda i: (i[0][1], i[1]))
print(c_sorted)

i[0][1] accesses the second element ([1]) of the sublist (i[0]) from a. This is the value you want to use for the initial sorting. i[1] accesses the corresponding element from b. This is the value you want to use as the secondary sorting criterion.