Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a tuple to a list - what's the difference between two ways?

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

like image 829
Skywalker326 Avatar asked Jul 02 '15 03:07

Skywalker326


People also ask

What are the two difference between list and tuple?

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.

Can you append a tuple to a list?

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 the difference between a tuple and a list explain with example?

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.

What are the similarities and differences between tuple and list?

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.


1 Answers

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

like image 186
Bhargav Rao Avatar answered Sep 21 '22 20:09

Bhargav Rao