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

Skywalker326 picture Skywalker326 · Jul 2, 2015 · Viewed 161k times · Source

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

Answer

Bhargav Rao picture Bhargav Rao · Jul 2, 2015

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