Merge and Sort Items of a Tuple in Python - Python Tutorial for Beginners

preview_player
Показать описание
🎓Welcome back to Digital Academy, the Complete Python Development Tutorial for Beginners, which will help you Learn Python from A to Z!

🖥️ Merge and Sort Items of a Tuple in Python

○ Merging two Tuples in Python

Although tuples are not changeable, you may sometimes want or need to merge two tuples, so that you can have all of your data located in the same variable. Or, even update its items, with new values. Fortunately, two tuples can be joined using the concatenation operator (+), or the augmented assignment operator (+=) to combine all of the items.

my_tuple = ('red', 'green', 'blue')

# Concatenation operator
my_tuple = my_tuple + (1,2,3)
# my_tuple = ('red', 'green', 'blue', 1, 2, 3)

# Augmented assignment operator
my_tuple += (1,2,3)
# my_tuple = ('red', 'green', 'blue', 1, 2, 3)

Notice: Tuples keep duplicate members, so this method does not overwrite existing values, and add them instead at the end.

○ Sorting a Tuple in Python

Awesome! But how would you proceed, if you need to rearrange items inside of your tuple? There are two methods to sort a tuple: using a built-in method, or convert it into a mutable object first, then rearrange it.

Method 1: Use the built-in sorted() method that accepts any sequence object as parameter.

my_tuple = ('red', 'green', 'blue', 'yellow')

my_tuple = tuple(sorted(my_tuple))
# my_tuple = ('blue', 'green', 'red', 'yellow')

Method 2: Convert a tuple into a mutable object like list, gain access to a sorting method call, and convert it back into a tuple.

my_tuple = ('red', 'green', 'blue', 'yellow')

my_list = list(my_tuple) # Convert tuple to list
my_tuple = tuple(my_list) # Convert back to tuple

# my_tuple = ('blue', 'green', 'red', 'yellow')

Let's play this video, stick around and watch until the end of this video! 👍🏻

- Digital Academy™ 🎓

***

☞ WATCH NEXT:

#Python #Tutorial #Beginners #Shorts

***

♡ Thanks for watching and supporting ♡
Please Subscribe. Hit the notification bell.
Like, Comment and Share.

***

♡ FOLLOW US ♡

♡ SUPPORT US ♡

***
Рекомендации по теме
Комментарии
Автор

How to Merge and Sort Tuples in Python? 🤔

DigitalAcademyOnline
Автор

Hope your channel will take the right path and become successful 🥰

xJrmy