top of page

Python Practice Set (Part 6): Slicing, Unpacking, and Set Logic


ree

Python Data in Action: Slicing, Unpacking, and Set Logic


Welcome back to our Python practice series! In this set, we're diving into practical, action-oriented challenges that showcase the power and elegance of Python's built-in data types. You'll learn how to clean up messy string data, extract specific subsets from lists, safely update dictionaries, and use the power of sets to compare data. These are the kinds of tasks you'll encounter daily as a developer. Let's get coding!


1. Cleaning and Standardizing a Phone Number (String Methods)


You are given a phone number as a string with inconsistent formatting: raw_phone = "(123) 456-7890". Your goal is to clean this string and reformat it to the international standard: +1-123-456-7890.

  • You will need to remove the parentheses, the space, and replace the first dash with the country code +1-.

Hint: Method chaining (string.replace().replace()...) can make your solution very concise.


2. Extracting a Sublist of High Scores (List Slicing)


You have a list of scores sorted in descending order: scores = [98, 95, 92, 88, 85, 81, 79, 75]. Your task is to create a new list called top_three that contains only the top three scores from the original list. Solve this using a single line of code with list slicing.


3. Safely Updating an Inventory Count (Dictionary .get() Method)


You are managing a product inventory stored in a dictionary: inventory = {'apples': 10, 'oranges': 5}. You need to write a function add_stock that takes the inventory dictionary, an item_name, and a quantity to add.

  • If the item already exists in the inventory, it should add the new quantity to the existing count.

  • If the item does not exist, it should add the item to the inventory with the given quantity.

Hint: Use the inventory.get(item_name, 0) method to safely get the current count, which returns 0 if the item doesn't exist.


4. Assigning Coordinates with Tuple Unpacking (Tuples)


A function returns a location as a tuple location = ("New York", 40.7128, -74.0060). Your task is to assign the city name, latitude, and longitude to three separate variables (city, latitude, longitude) in a single line of code using tuple unpacking. Print each of the three new variables.


5. Finding Mutual Friends (Set Intersection)


You have two lists of friends for two different users. user1_friends = ["Alice", "Bob", "Charlie", "David"]user2_friends = ["Eve", "Frank", "Charlie", "Alice"]

Find all the friends that both users have in common and store them in a list called mutual_friends.

Hint: Convert the lists to sets and use the intersection operator (&).



Comments


bottom of page