'Python: List of tuples [duplicate]
Please, if I have a list of tuples, say:
list = [('James', 27, 2000), ('Aaron', 24, 1290), ('Max', 23, 2300), ('Ben', 27, 1900)]
How do I get all the names in ascending order?
How do I get a list that shows the tuples in ascending order of names?
Thanks
Solution 1:[1]
If you sort a list of tuples, by default the first item in the tuple is taken as the key. Therefore:
list_ = [('James', 27, 2000), ('Aaron', 24, 1290), ('Max', 23, 2300), ('Ben', 27, 1900)]
for name, *_ in sorted(list_):
print(name)
Output:
Aaron
Ben
James
Max
Or, if you want the tuples then:
for t in sorted(list_):
print(t)
...which produces:
('Aaron', 24, 1290)
('Ben', 27, 1900)
('James', 27, 2000)
('Max', 23, 2300)
Solution 2:[2]
Assuming by ascending you mean alphabetical?
You can do it with sorted:
a = [('James', 27, 2000), ('Aaron', 24, 1290), ('Max', 23, 2300), ('Ben', 27, 1900)]
sorted(a, key=lambda x: x[0])
Output:
[('Aaron', 24, 1290),
('Ben', 27, 1900),
('James', 27, 2000),
('Max', 23, 2300)]
Solution 3:[3]
lst = [('James', 27, 2000), ('Aaron', 24, 1290), ('Max', 23, 2300), ('Ben', 27, 1900)]
print(sorted(lst))
Prints
[('Aaron', 24, 1290), ('Ben', 27, 1900), ('James', 27, 2000), ('Max', 23, 2300)]
Solution 4:[4]
list = [('James', 27, 2000), ('Aaron', 24, 1290), ('Max', 23, 2300), ('Ben', 27, 1900)]
sorted_names = sorted([i[0] for i in list])
print(sorted_names)
Output:
['Aaron', 'Ben', 'James', 'Max']
sorted_by_name = sorted(list, key=lambda tup: tup[0])
print(sorted_by_name)
Output:
[('Aaron', 24, 1290), ('Ben', 27, 1900), ('James', 27, 2000), ('Max', 23, 2300)]
Solution 5:[5]
>>> l = [('James', 27, 2000), ('Aaron', 24, 1290), ('Max', 23, 2300), ('Ben', 27, 1900)]
>>> sorted([name for name, _, _ in l])
['Aaron', 'Ben', 'James', 'Max']
>>> sorted(l)
[('Aaron', 24, 1290), ('Ben', 27, 1900), ('James', 27, 2000), ('Max', 23, 2300)]
Be advised that list is an object in Python, so when you create a variable with the name list, you overwrite that reference and you cannot use list(something) after in your program.
Solution 6:[6]
You can use key parameter in sort or sorted function. Here's an example:
my_list = [('James', 27, 2000), ('Aaron', 24, 1290), ('Max', 23, 2300), ('Ben', 27, 1900)]
my_list_sorted_by_names = sorted(my_list, key=lambda x: x[0])
And the result will be:
[('Aaron', 24, 1290), ('Ben', 27, 1900), ('James', 27, 2000), ('Max', 23, 2300)]
You can use list comprehension to extract names from sorted list:
ordered_names = [i[0] for i in my_list_sorted_by_names]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Albert Winestein |
| Solution 2 | Nin17 |
| Solution 3 | gremur |
| Solution 4 | Phantoms |
| Solution 5 | Nilton Moura |
| Solution 6 | Mateusz Matelski |
