Sort the list (or)Tuples with the element at given index

Submitted 3 years, 6 months ago
Ticket #226
Views 229
Language/Framework Python
Priority Medium
Status Closed

For example:

I have a list of tuples like:

data = [(1,2,3), (4,3,6), (7,0,9)]

I want the output as:

[(7, 0, 9), (1, 2, 3), (4, 3, 6)]

In the output you can the tuples are sorted in ascending order based on index[1]

Submitted on Oct 10, 20
sai
add a comment

2 Answers

Verified

index={}

data = [(1,2,3), (4,3,6), (7,0,9)]

for i in range(0,len(data)):
  index[data[i][1]]=i

for i in sorted(index):
  print(data[index[i]])

Submitted 3 years, 6 months ago

data = [(1,2,3), (4,3,6), (7,0,9)]
sorted_by_second = sorted(data, key=lambda tup: tup[1])
print(sorted_by_second)

Submitted 3 years, 6 months ago


Latest Blogs