-3

I am currently trying to solve a problem involving lists and sorting (i.e.) when a list (not a normal one ,but a list of tuple ) is entered ; the program should print out the list but in an orderly(increasing order) manner based on the 2nd elements of each tuples. ex: Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)] Here is what I have tried until now:

def sorting(L):
le=len(L)
G=[]
Lnew=[list(l) for l in L]
for i in range(le):
    G.append(Lnew[i][1])
    G.sort()
    Lnew.remove(Lnew[i][1]) #where the problem is
    for k in range(len(G)):
        Lnew[k][1]=G[k]
        for elt in Lnew:
            tuple(elt)
return L

An error displays "list.remove(x): x not in list" . how do I proceed in that case? or is there a simpler way to tackle the problem ?

  • 2
    Don't re-invent the wheel; use `sorted` or `list.sort` with an appropriate `key` function. See https://docs.python.org/3/howto/sorting.html. About `Lnew.remove(Lnew[i][1])`: `Lnew` contains `Lnew[i]`, but not `Lnew[i][1]`. – tobias_k Nov 17 '21 at 17:56
  • One point about your variables: Avoid using `l` (lowercase `L` ) as a variable, see [The official pep8 style guidleines](https://www.python.org/dev/peps/pep-0008/#names-to-avoid) and for your own sanity avoid naming variables like `l`, `L`, `el`, `le` in the same script, this can only lead to confusion if you have to re-read your own code later – G. Anderson Nov 17 '21 at 17:59

2 Answers2

1
from operator import itemgetter
lista_of_tuples = sorted(list_of_tuples, key_itemgetter(0))

itemgetter parameter can be 0,1,2 depending which one to order it by

Zoe
  • 27,060
  • 21
  • 118
  • 148
0
def sorting(my_list):
    return sorted(my_list, key=lambda x: x[1])

sorting([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)])  

Output: [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
Maximilian Freitag
  • 939
  • 2
  • 10
  • 26