0

Please, if I have a list of tuples, say:

list = [('James', 27, 2000), ('Aaron', 24, 1290), ('Max', 23, 2300), ('Ben', 27, 1900)]

  1. How do I get all the names in ascending order?

  2. How do I get a list that shows the tuples in ascending order of names?

Thanks

greg616
  • 57
  • 4

6 Answers6

0

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)
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0

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)]
Nin17
  • 2,821
  • 2
  • 4
  • 14
0
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)]
gremur
  • 1,645
  • 2
  • 7
  • 20
0
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)]
Phantoms
  • 145
  • 5
0
>>> 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.

Nilton Moura
  • 313
  • 2
  • 8
0

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]