You can use lambda
for that:
a = [('1253', 'Fred'), ('1389', 'Sally'), ('889', 'Sue')]
b = sorted(a, key=lambda a: int(a[0]))
Your case
>>> EmpList = [('1253', 'Fred'), ('889', 'Sue'), ('1389', 'Sally')]
>>> b = sorted(a, key=lambda EmpList: int(EmpList[0]))
>>> b
[('889', 'Sue'), ('1253', 'Fred'), ('1389', 'Sally')]
To get reversed values, you can do:
>>> EmpList = [('1253', 'Fred'), ('889', 'Sue'), ('1389', 'Sally')]
>>> b = sorted(a, key=lambda EmpList: int(EmpList[0]), reversed=True)
>>> b
[('1389', 'Sally'), ('1253', 'Fred'), ('889', 'Sue')]
Note
Note the importance of casting the a[0]
as an int. This is because if you do not cast it as an int, python will do the comparisons on string and:
>>> '889' > '1253'
True
This is because when python compares the first character of each string, '8' is greater than '1' and therfore, '889' > '1253'
evaluates to True.
This is definitely not what you want. So to do it properly, cast it as int
.