w3resource

Python program to filter cities by population


Write a Python program that creates a list of tuples, each containing a city name and its population. Use the filter function to extract cities with a population greater than 2 million.

Sample Solution:

Python Code:

# Define a list of city-population tuples
cities = [
    ("New York", 8500000),
    ("Los Angeles", 4000000),
    ("Chicago", 2700000),
    ("Houston", 2300000),
    ("Phoenix", 1600000),
    ("Philadelphia", 1500000),
    ("San Antonio", 1500000),
]

print("list of city and population:")
print(cities)
# Define a function to check if a city has a population greater than 2 million
def has_population_greater_than_two_million(city_population):
    return city_population[1] > 2000000

# Use the filter function to extract cities with a population greater than two million
million_plus_cities = list(filter(has_population_greater_than_two_million, cities))

print("\nExtract cities with a population greater than 2 million:")
# Print the extracted cities
print(million_plus_cities)

Explanation:

In the exercise above -

  • First, we start with a list of city-population tuples called 'cities'.
  • Define a function called "has_population_greater_than_two_million()" that checks if a city's population (the second element of each tuple) is greater than 2 million.
  • We use the filter function to filter out cities from the cities list based on the condition defined by the "has_population_greater_than_two_million()" function.
  • Finally, the filtered cities with a population greater than 2 million are converted to a list, and we print the extracted cities.

Sample Output:

list of city and population:
[('New York', 8500000), ('Los Angeles', 4000000), ('Chicago', 2700000), ('Houston', 2300000), ('Phoenix', 1600000), ('Philadelphia', 1500000), ('San Antonio', 1500000)]

Extract cities with a population greater than 2 million:
[('New York', 8500000), ('Los Angeles', 4000000), ('Chicago', 2700000), ('Houston', 2300000)]

Flowchart:

Flowchart: Python program to filter future dates.

Python Code Editor:

Previous: Python program to filter future dates.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.