Python program to sort table based on given attribute index

Suppose we have a 2D list containing information about athletes. This information includes rank, age, and height. Each row contains data for different athletes. We need to sort the table based on a given attribute index k.

So, if the input is like ?

Rank Age Height
1 25 190
2 35 180
3 33 185
4 26 175
5 35 180

And k = 1 (sort by age), then the output will be ?

Rank Age Height
1 25 190
4 26 175
3 33 185
2 35 180
5 35 180

Approach

To solve this problem, we will ?

  • Use the sort() method with a lambda function as the key parameter
  • The lambda function will extract the element at index k from each row for comparison
  • The sort() method will arrange rows in ascending order based on the kth attribute

Example

Let us see the following implementation to get better understanding ?

def solve(info, k):
    info.sort(key=lambda x: x[k])
    return info

# Sample data: [rank, age, height]
athletes_data = [[1, 25, 190], [2, 35, 180], [3, 33, 185], [4, 26, 175], [5, 35, 180]]
k = 1  # Sort by age (index 1)

result = solve(athletes_data, k)
print("Sorted by age:")
for row in result:
    print(row)
Sorted by age:
[1, 25, 190]
[4, 26, 175]
[3, 33, 185]
[2, 35, 180]
[5, 35, 180]

Sorting by Different Attributes

You can sort by any attribute by changing the value of k ?

def sort_table(data, attribute_index):
    data.sort(key=lambda x: x[attribute_index])
    return data

# Sample data
athletes = [[1, 25, 190], [2, 35, 180], [3, 33, 185], [4, 26, 175], [5, 35, 180]]

# Sort by rank (index 0)
print("Sort by rank:")
result1 = sort_table(athletes.copy(), 0)
print(result1)

# Sort by height (index 2)  
print("\nSort by height:")
result2 = sort_table(athletes.copy(), 2)
print(result2)
Sort by rank:
[[1, 25, 190], [2, 35, 180], [3, 33, 185], [4, 26, 175], [5, 35, 180]]

Sort by height:
[[4, 26, 175], [2, 35, 180], [5, 35, 180], [3, 33, 185], [1, 25, 190]]

Key Points

  • The lambda x: x[k] function extracts the element at index k from each row
  • The sort() method modifies the original list in-place
  • Use list.copy() if you want to preserve the original data
  • The sorting is stable, meaning equal elements maintain their relative order

Conclusion

Sorting a 2D list by a specific attribute index is efficiently accomplished using Python's sort() method with a lambda function. This approach allows flexible sorting by any column index in the table.

Updated on: 2026-03-26T15:43:11+05:30

473 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements