Last active
June 3, 2023 16:48
-
-
Save eder-projetos-dev/65ce46cc4a14c61990d40f9630f250ee to your computer and use it in GitHub Desktop.
Python - Tuple unpacking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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