0

I have a 2D list:

[['Hard', '7', '27.00'], ['David', '4', '26.00'], ['Great', '2', '25.00']]

I want to print it out in alphabetical order based on the first index of each list. I have a variable called listName which stores the information as presented above. I have tried listName.sort() however, it does not sort in alphabetical order. Any suggestions?

2 Answers 2

1

You have to pass a key argument to sort(). This function will sort the elements (in your case, each element is a list) based on the first item (x[0]) of that element:

listName.sort(key = lambda x:x[0])

Note: This will sort the lists based on an ASCII comparison (please, correct me if I'm wrong), therefore, it will put uppercase before lowercase. For example:

listName = [['Hard', '7', '27.00'], ['David', '4', '26.00'], ['Great', '2', '25.00'], ['a', '3', '123']]
listName.sort(key = lambda x:x[0])
print(listName)
# [['David', '4', '26.00'], ['Great', '2', '25.00'], ['Hard', '7', '27.00'], ['a', '3', '123']]
Sign up to request clarification or add additional context in comments.

4 Comments

Explanation: This selects the first entry of each sub-list to be used for comparison when sorting.
@Christian is there any other way to do this. I havent learned about lambdas yet
@novicecoder Why that mentality? This demonstrates the simplicity, and practical use of lambdas. Instead, learn about them now.
Anyways, a lambda function can be written as a normal function. So, if you have learned about functions, you can use it instead.
0

Two more options:

# The data
listName = [['Hard', '7', '27.00'], ['David', '4', '26.00'], ['Great', '2', '25.00'], ['a', '3', '123']]


# Use first element for sorting using operator.itemgetter (like x[0])
from operator import itemgetter
sorted(listName, key=itemgetter(0))


# Use a function instead of a lambda (+ case insensitive sorting)
def get(x):
    # return first element of sublist and convert to lowercase
    return x[0].lower()

sorted(listName, key=get)

Lambdas and function are very similar:

lambda x: x[0]

def get(x): return x[0]

The difference is that functions have a name and lambdas are anonymous (unless stored in a variable). You must not use return in a lambda, its behavior is always like there is one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.