How to unpack Python list or tuple the better way?
Draft
29 April, 2022
Contributors
In this blog, we will discuss how to use unpacking to assign multiple items from a list/tuple instead of manually accessing and setting the values.
What we generally do
Generally, whenever we encounter a list or tuple in Python and we need to unpack it, we do it this way:
Yep, we’re able to access the list elements correctly. It’s not wrong at all. But there’s a better way to do the same.
The Better Way
The same task can be performed in a better way. Instead of manually accessing and setting the values, we can assign multiple items from a list/tuple this way:
Did you see that we got the same output but with lesser code? It’s more concise and less error-prone.
If you know JavaScript, you might have found it similar to destructuring there.
Let’s see another example where we have a tuple within the list.
In the above example, we have a list called post_data
. Inside the list, we have a tuple containing author data.
We have a general way first. Then we have our better way where first of all, we unpacked the list to get the post_id
, post_title
, and author_data
(which is a tuple). Then we unpacked the tuple to get the author_name
, author_age
, and author_country
.
In this short blog, we saw how we can unpack lists or tuples in a better concise, and less error-prone way.
Let me know your thoughts in the comments.