Sort a Python List of Tuples by the First Element

Handling data efficiently is a core part of my daily routine as a Python developer. Over the last decade, I have found that tuples are one of the most reliable ways to store structured information.

Recently, I was working on a project involving US Census data. I needed to organize a large list of cities and their populations, but the data was completely unsorted. Sorting a Python list of tuples by the first element is a task you will encounter frequently.

In this tutorial, I will show you exactly how I handle this using various Python methods. I have designed these examples using real-world data to make the concepts stick.

Python List of Tuples Structure

Before we jump into the code, let’s look at what we are actually trying to organize. A Python list of tuples looks like a collection of fixed rows.

Imagine we have a list of US states paired with their respective area codes. Each tuple contains the state name as the first element and the code as the second.

By default, Python’s sorting mechanisms are quite smart. If you ask Python to sort a list of tuples, it starts with the first element of each tuple automatically.

1. Use the Python sort() Method

The most direct way I sort data when I don’t need to keep the original list order is by using the sort() method. This is an “in-place” operation.

When I use sort(), Python modifies the existing list directly. This is highly memory-efficient when working with large datasets like US ZIP code registries.

# List of US Cities and their founding years
us_cities = [
    ("Philadelphia", 1682),
    ("Boston", 1630),
    ("New York City", 1624),
    ("St. Augustine", 1565),
    ("Santa Fe", 1610)
]

# Using the Python sort() method to sort by the city name (index 0)
us_cities.sort()

print("Cities sorted alphabetically:")
for city in us_cities:
    print(city)

You can refer to the screenshot below to see the output.

python sort list of tuples by first element

In this example, Python looks at the first element (the city name). It compares “Philadelphia” to “Boston” and rearranges them in ascending alphabetical order.

2. Sort with the Python sorted() Function

I often find myself in situations where I need to keep my original data intact while creating a new, sorted version. For this, I always reach for the sorted() function.

The sorted() function is a built-in Python tool that returns a brand-new list. This is perfect for data analysis workflows where you might need to reference the raw data later.

# US Stock Tickers and their prices
stock_data = [
    ("AAPL", 185.92),
    ("MSFT", 415.10),
    ("AMZN", 174.42),
    ("GOOGL", 152.12),
    ("TSLA", 175.34)
]

# Creating a new sorted list using Python sorted()
sorted_stocks = sorted(stock_data)

print("Original Stock Data:")
print(stock_data)

print("\nSorted Stock Data (by Ticker):")
print(sorted_stocks)

You can refer to the screenshot below to see the output.

python sort by first element in tuple

Because “AAPL” starts with ‘A’, it stays at the top. The sorted() function is my go-to when I am building Python web applications that display data in different views.

3. Use a Lambda Function for Explicit Sorting

Sometimes, being explicit in your code makes it more readable for your team. I frequently use Python lambda functions to define exactly which element I want to sort by.

Even though Python sorts by the first element by default, using key=lambda x: x[0] tells anyone reading your code, “I am specifically sorting by the first item.”

Here is how I apply this to a list of US Presidential names and their terms:

# US Presidents and their order of service
presidents = [
    ("George Washington", 1),
    ("Abraham Lincoln", 16),
    ("Thomas Jefferson", 3),
    ("Theodore Roosevelt", 26),
    ("John F. Kennedy", 35)
]

# Using a lambda function to target the first element explicitly
presidents.sort(key=lambda president: president[0])

print("Presidents sorted alphabetically by first name:")
for p in presidents:
    print(p)

You can refer to the screenshot below to see the output.

sort list of tuples by first element python

I prefer this method because it is highly flexible. If I suddenly decided to sort by the term number instead, I would just change x[0] to x[1].

4. Sort in Reverse Order

In many US business applications, you might need to show the most recent or “highest” alphabetical values first. Both sort() and sorted() accept a reverse parameter.

When I set reverse=True, Python flips the order. This is incredibly useful for ranking systems or countdowns.

# US States and their electoral votes
electoral_votes = [
    ("California", 54),
    ("Texas", 40),
    ("Florida", 30),
    ("New York", 28),
    ("Illinois", 19)
]

# Sorting alphabetically in reverse (Z to A)
electoral_votes.sort(key=lambda x: x[0], reverse=True)

print("States in reverse alphabetical order:")
for state in electoral_votes:
    print(state)

You can refer to the screenshot below to see the output.

python sort list of tuples

5. Leverage itemgetter for Faster Sorting

When I am dealing with massive datasets, think millions of rows of US tax data, I stop using lambda functions. Instead, I use operator.itemgetter.

In my experience, itemgetter is significantly faster than a lambda function. This is because it is implemented in C at the Python level.

To use this, you need to import the operator module. Here is a professional example:

from operator import itemgetter

# US Airline codes and their main hubs
airlines = [
    ("Delta", "Atlanta"),
    ("United", "Chicago"),
    ("American", "Dallas"),
    ("Southwest", "Dallas"),
    ("JetBlue", "New York")
]

# Using itemgetter to sort by the first element (index 0)
airlines.sort(key=itemgetter(0))

print("Airlines sorted by name using itemgetter:")
for airline in airlines:
    print(airline)

If performance is your priority, I highly recommend getting comfortable with itemgetter. It has saved me hours of processing time on heavy Python backends.

Handle Case Sensitivity in Python Sorting

A common trap I see junior developers fall into is ignoring case sensitivity. In Python, uppercase letters come before lowercase letters in the ASCII table.

If your list of tuples contains “atlanta” and “Boston,” “Boston” will appear first because of the capital ‘B’. To fix this, I use a method call within the key.

# Mixed case US Landmarks
landmarks = [
    ("grand canyon", "Arizona"),
    ("Statue of Liberty", "New York"),
    ("mount rushmore", "South Dakota"),
    ("Golden Gate Bridge", "California")
]

# Sorting without case sensitivity
landmarks.sort(key=lambda x: x[0].lower())

print("Case-insensitive sorting:")
for landmark in landmarks:
    print(landmark)

By applying .lower(), I ensure that the Python sorting logic treats ‘g’ and ‘G’ as the same value. This makes the data much more user-friendly for people living in the US who expect standard alphabetical order.

Sort Lists of Tuples with Multiple Criteria

While your main goal might be sorting by the first element, you might encounter “ties.” For example, if you have two cities with the same name in different states.

Python’s sorting is “stable,” meaning it preserves the original order of items that compare equal. However, I often specify a second sorting criterion just in case.

# US City and State tuples (handling duplicate city names)
locations = [
    ("Springfield", "Illinois"),
    ("Springfield", "Missouri"),
    ("Springfield", "Massachusetts"),
    ("Portland", "Oregon"),
    ("Portland", "Maine")
]

# Sort by first element (City), then by second element (State)
locations.sort(key=lambda x: (x[0], x[1]))

print("Sorted by City, then State:")
for loc in locations:
    print(loc)

This technique is a lifesaver when organizing complex US geographic data.

I hope this guide helps you understand the different ways to sort a list of tuples in Python. Whether you choose the simple sort() method or the high-performance itemgetter, each approach has its own place in a developer’s toolkit.

In most cases, I recommend using the sorted() function if you want to keep your data safe, or the sort() method if you are looking for efficiency. Experiment with these methods using your own datasets to see which one works best for your specific project.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.