Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eder-projetos-dev/65ce46cc4a14c61990d40f9630f250ee to your computer and use it in GitHub Desktop.
Save eder-projetos-dev/65ce46cc4a14c61990d40f9630f250ee to your computer and use it in GitHub Desktop.
Python - Tuple unpacking
# Traditional approach
point = (3, 7)
x = point[0]
y = point[1]
# Tuple unpacking
x, y = point
# Pro Tip: When unpacking tuples, you can use an asterisk (*) to capture multiple elements into a single variable.
# This is particularly useful when dealing with variable-length tuples.
# Unpacking with an asterisk
first, *middle, last = [1, 2, 3, 4, 5]
print(middle) # Output: [2, 3, 4]
@eder-projetos-dev
Copy link
Author

eder-projetos-dev commented Jun 3, 2023

How can I leverage tuple unpacking to enhance my code?

Tuples are a handy way to store multiple values in Python. However, extracting values from a tuple can sometimes be a tedious task. That’s where tuple unpacking comes to the rescue! It allows you to assign the individual elements of a tuple to separate variables in a single line.

Tuple unpacking is a handy technique that I think every Python developer should be familiar with. It simplifies the process of working with tuples and makes your code more concise and readable. Whenever you have a tuple and need to extract its elements into separate variables, consider using tuple unpacking. It will make your code cleaner and more efficient.

https://levelup.gitconnected.com/11-tricks-that-will-make-your-life-easier-as-a-python-developer-da29e4306675

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment