Search code examples
pythonlisttuplesdatasetanalytics

Python: List of tuples


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


Solution

  • 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)