Tuples in Python are immutable sequences, which means once created, their contents cannot be altered. They are often used for storing related but different data items. Despite their immutability, tuples can be used in advanced ways for various purposes such as data grouping, key-value pairing, and more. Let’s explore an advanced example using tuples.
You are building an application that deals with geographic locations and you need to store information about several cities. For each city, you’ll store its name, country, latitude, and longitude. This information should be stored in a data structure that prevents accidental modification. Moreover, you want to analyze the data to find out which cities are closest to a given reference point.
We’ll use tuples to store information about each city. By leveraging tuples:
Each city will be represented by a tuple consisting of its name, country, latitude, and longitude.
cities = [
("New York", "USA", 40.7128, -74.0060),
("Los Angeles", "USA", 34.0522, -118.2437),
("Tokyo", "Japan", 35.6895, 139.6917),
("Sydney", "Australia", -33.8688, 151.2093),
("Paris", "France", 48.8566, 2.3522),
("London", "UK", 51.5074, -0.1278)
]
We’ll use the Haversine formula to compute the distance between two points on the globe given their latitudes and longitudes.
from math import radians, sin, cos, sqrt, atan2
def haversine(lat1, lon1, lat2, lon2):
# Convert latitude and longitude from degrees to radians
lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])
# Haversine formula
dlat = lat2 - lat1
dlon = lon2 - lon1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
radius = 6371 # Earth's radius in kilometers
return radius * c
The function find_nearest_city will take a reference latitude and longitude and find the nearest city from the list of cities.
def find_nearest_city(ref_lat, ref_lon, cities):
nearest_city = None
min_distance = float('inf')
for city in cities:
name, country, lat, lon = city
distance = haversine(ref_lat, ref_lon, lat, lon)
if distance < min_distance:
nearest_city = city
min_distance = distance
return nearest_city, min_distance
Let’s find the nearest city to a given reference point (e.g., latitude 37.7749 and longitude -122.4194 for San Francisco).
reference_point = (37.7749, -122.4194)
nearest_city, distance = find_nearest_city(reference_point[0], reference_point[1], cities)
print(f"Nearest city: {nearest_city[0]}, {nearest_city[1]}")
print(f"Distance: {distance:.2f} km")
Nearest city: Los Angeles,
USA Distance: 559.52 km
cities = [
("New York", "USA", 40.7128, -74.0060),
("Los Angeles", "USA", 34.0522, -118.2437),
("Tokyo", "Japan", 35.6895, 139.6917),
("Sydney", "Australia", -33.8688, 151.2093),
("Paris", "France", 48.8566, 2.3522),
("London", "UK", 51.5074, -0.1278)
]
cities, holds tuples where each tuple represents a city. A tuple contains four elements: the city name, country name, latitude, and longitude."New York"."USA".40.7128.-74.0060.The use of tuples ensures that the data remains immutable, preventing accidental modifications.
from math import radians, sin, cos, sqrt, atan2
def haversine(lat1, lon1, lat2, lon2):
# Convert latitude and longitude from degrees to radians
lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])
# Haversine formula
dlat = lat2 - lat1
dlon = lon2 - lon1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
radius = 6371 # Earth's radius in kilometers
return radius * c
haversine function calculates the great-circle distance between two points on the Earth specified by their latitude and longitude. This is done using the Haversine formula.lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])dlat) and longitudes (dlon).def find_nearest_city(ref_lat, ref_lon, cities):
nearest_city = None
min_distance = float('inf')
for city in cities:
name, country, lat, lon = city
distance = haversine(ref_lat, ref_lon, lat, lon)
if distance < min_distance:
nearest_city = city
min_distance = distance
return nearest_city, min_distance
find_nearest_city function finds the city closest to the given reference point (ref_lat, ref_lon) from the list of cities.nearest_city: Initially None, to store the closest city.min_distance: Initially set to infinity (float('inf')), to keep track of the shortest distance found.name, country, lat, and lon.haversine function to calculate the distance between the reference point and the current city’s coordinates.min_distance, update nearest_city and min_distance.reference_point = (37.7749, -122.4194)
nearest_city, distance = find_nearest_city(reference_point[0], reference_point[1], cities)
print(f"Nearest city: {nearest_city[0]}, {nearest_city[1]}")
print(f"Distance: {distance:.2f} km")
find_nearest_city function.reference_point as the coordinates for San Francisco.find_nearest_city with the latitude and longitude of the reference point and the list of cities.nearest_city tuple to print the city’s name and country.