How to unpack Python list or tuple the better way?
# Introduction
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:
post_data = [1, 'Getting started with Rich', 'Ashutosh Krishna']
post_id = post_data[0]
post_title = post_data[1]
post_author = post_data[2]
print(post_id, post_title, post_author)
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:
post_data = [1, 'Getting started with Rich', 'Ashutosh Krishna']
post_id, post_title, post_author = post_data
print(post_id, post_title, post_author)
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.
const postData = [1, "Getting Started With Rich", "Ashutosh Krishna"];
const [postId, postTitle, postAuthor] = postData;
console.log(postId, postTitle, postAuthor);
// With Objects
const anotherPostData = {
anotherPostId: 1,
anotherPostTitle: "Getting Started With Rich",
anotherPostAuthor: "Ashutosh Krishna",
};
const { anotherPostId, anotherPostTitle, anotherPostAuthor } = anotherPostData;
console.log(anotherPostId, anotherPostTitle, anotherPostAuthor);
Let's see another example where we have a tuple within the list.
post_data = [1, 'Getting started with Rich', ('Ashutosh Krishna', 22, 'India')]
## General Way, Don't Do ❌
post_id = post_data[0]
post_title = post_data[1]
author_data = post_data[2]
author_name = author_data[0]
author_age = author_data[1]
author_country = author_data[2]
print(post_id, post_title)
print(author_name, author_age, author_country)
## Better Way ✅
## Unpack the list first
post_id, post_title, author_data = post_data
## Unpack the tuple
author_name, author_age, author_country = author_data
print(post_id, post_title)
print(author_name, author_age, author_country)
In the above example, we have a list called post_data
. Inside the list, we have a tuple containing author data.
We have the 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
.
Conclusion
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.