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

PythonListTypesAppendTuples

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

Because tuple(3, 4) is not the correct syntax to create a tuple. The correct syntax is -

tuple([3, 4])

or

(3, 4)

You can see it from here - https://docs.python.org/2/library/functions.html#tuple

Solution 3 - Python

I believe tuple() takes a list as an argument For example,

tuple([1,2,3]) # returns (1,2,3)

see what happens if you wrap your array with brackets

Solution 4 - Python

There should be no difference, but your tuple method is wrong, try:

a_list.append(tuple([3, 4]))

Solution 5 - Python

It has nothing to do with append. tuple(3, 4) all by itself raises that error.

The reason is that, as the error message says, tuple expects an iterable argument. You can make a tuple of the contents of a single object by passing that single object to tuple. You can't make a tuple of two things by passing them as separate arguments.

Just do (3, 4) to make a tuple, as in your first example. There's no reason not to use that simple syntax for writing a tuple.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSkywalker326View Question on Stackoverflow
Solution 1 - PythonBhargav RaoView Answer on Stackoverflow
Solution 2 - Pythonbrainless coderView Answer on Stackoverflow
Solution 3 - PythonAshwin ReddyView Answer on Stackoverflow
Solution 4 - Python101View Answer on Stackoverflow
Solution 5 - PythonBrenBarnView Answer on Stackoverflow