Add and Update Values from a Tuple in Python (Convert into List)

https://www.youtube.com/watch?v=INHvRWzsrjU

🎓 Welcome back to Digital Academy, the Complete Python Development Tutorial for Beginners, which will help you Learn Python from A to Z!

🖥️ Add and Update Values from a Tuple in Python (Convert into List)

As you know: Tuples in Python are immutable. Once a tuple has been created, it cannot be modified afterwards or it would trigger an error: TypeError exception. That’s what it costs if you want to increase security and speed when manipulating tuples!

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

my_tuple[0] = 'black'
# Triggers TypeError: 'tuple' object does not support item assignment


○ How to Add and Update a Value from Tuple in Python?

Consequently, when you use this kind of data type, you are not supposed to add, update or remove items from a tuple. But, there is a workaround: You can convert the tuple into a list, change the list, then convert the list back into a tuple!

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

my_tuple = list(my_tuple) # my_tuple = ['red', 'green', 'blue']
my_tuple[0] = 'black' # my_tuple = ['black', 'green', 'blue']
my_tuple = tuple(my_tuple) # my_tuple = ('black', 'green', 'blue')


Note: The tuple immutability is applicable only to the Top level of the tuple itself, not to its contents. For example, a list inside a tuple can be changed as usual with indexing, without even converting the tuple into a list first.

my_tuple = (1, [2, 3], 4)
my_tuple[1][0] = 'abc'

# my_tuple = (1, ['abc', 3], 4)


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

– Digital Academy™ 🎓

***

☞ WATCH NEXT:
○ Data Types in Python – https://youtu.be/cweUByxBWiU
○ Operators in Python – https://youtu.be/-wDaVLkKOiU
○ IF Statements in Python – https://youtu.be/CC5seZ6OBJ4
○ FOR Loops in Python – https://youtu.be/JgH-D5DSTho

☞ WATCH MORE:
○ HOW TO Learn Python? Python Tutorial for Beginners [FULL Course] https://youtu.be/9hvnSZPMtuw

📖 Blog: http://digital.academy.free.fr/blog/

📖 Complete Python Development Course for Beginners [PLAYLIST]: http://digital.academy.free.fr/playlist/python-development-for-beginners

🛒 Shopping and Discounts: http://digital.academy.free.fr/store/

#Python #Tutorial #Beginners #Shorts

***

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

***

♡ FOLLOW US ♡
http://digital.academy.free.fr/
https://twitter.com/DigitalAcademyy
https://www.facebook.com/digitalacademyfr
https://www.instagram.com/digital_academy_fr/
https://www.youtube.com/c/DigitalAcademyOnline

♡ SUPPORT US ♡
http://digital.academy.free.fr/join
http://digital.academy.free.fr/donate
http://digital.academy.free.fr/subscribe
https://www.patreon.com/digital_academy
https://www.buymeacoffee.com/digital_academy

***

Copy link
Powered by Social Snap