How do you extract part of a numeric tuple with Python

How do you extract part of a numeric tuple with Python
python
Ethan Jackson

I am stuck on one exercise to extract the lat lon from a tuple and print lat lon on separate lines.

nyc_data = {'city': 'New York', 'population': 8175133, 'coordinates': (40.661, -73.944) } print(nyc_data['coordinates'])

which produces

(40.661, -73.944)

I assigned 'New York' to a variable and was able to slice 'New' but when I tried this on a numeric value it only reproduces the whole number. How do you slice a numeric value in a tuple?

Answer

nyc_data = {'city': 'New York', 'population': 8175133, 'coordinates': (40.661, -73.944)} # Access the coordinates tuple coords = nyc_data['coordinates'] # Extract latitude and longitude lat = coords[0] # First element (40.661) lon = coords[1] # Second element (-73.944) # Print on separate lines print(lat) print(lon)

To extract and print the latitude and longitude from the coordinates tuple in nyc_data on separate lines, you can access the tuple elements by their index. A tuple (40.661, -73.944) has two elements: index 0 for latitude (40.661) and index 1 for longitude (-73.944). Unlike strings, you cannot "slice" individual digits or parts of a numeric value (like a float) directly, but you can extract the numbers from the tuple and print them.
Here's the output of the above example:

40.661 -73.944
  1. nyc_data['coordinates'] gives the tuple (40.661, -73.944).

  2. Use indexing (coords[0] and coords[1]) to get the individual float values.

  3. Numeric values (like 40.661) are not strings, so you can't slice them like you did with 'New York' to get 'New'. If you need to manipulate the digits of a number, convert it to a string first (e.g., str(40.661)), then slice the string, but that doesn't seem to be your goal here.

  4. The print() function automatically adds a newline after each call, so lat and lon appear on separate lines.

    Alternative: Tuple Unpacking

    You can also use tuple unpacking to assign lat and lon directly

Related Articles