I wrote my first "Hello World" 4 months ago. Since then, I have been following a Coursera Python course provided by Rice University. I recently worked on a mini-project involving tuples and lists. There is something strange about adding a tuple into a list for me:
a_list = [] a_list.append((1, 2)) # Succeed! Tuple (1, 2) is appended to a_list a_list.append(tuple(3, 4)) # Error message: ValueError: expecting Array or iterable
It's quite confusing for me. Why specifying the tuple to be appended by using "tuple(...)" instead of simple "(...)" will cause a ValueError
?
BTW: I used CodeSkulptor
coding tool used in the course
The key takeaways are; The key difference between the tuples and lists is that while the tuples are immutable objects the lists are mutable. This means that tuples cannot be changed while the lists can be modified. Tuples are more memory efficient than the lists.
In Python, we can easily add a tuple to a list with the list extend() function. You can also use the += operator to append the items of a tuple to a list in Python. When working with collections of data in Python, the ability to add and remove elements from an object easily is very valuable.
What is a Tuple in Python? A Tuple is also a sequence data type that can contain elements of different data types, but these are immutable in nature. In other words, a tuple is a collection of Python objects separated by commas. The tuple is faster than the list because of static in nature.
We can conclude that although both lists and tuples are data structures in Python, there are remarkable differences between the two, with the main difference being that lists are mutable while tuples are immutable. A list has a variable size while a tuple has a fixed size.
The tuple
function takes only one argument which has to be an iterable
tuple([iterable])
Return a tuple whose items are the same and in the same order as iterable‘s items.
Try making 3,4
an iterable by either using [3,4]
(a list) or (3,4)
(a tuple)
For example
a_list.append(tuple((3, 4)))
will work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With