Add a tuple to the list - what's the difference between the two methods?

I wrote my first "Hello World" 4 months ago. Since then, I have been following the Coursera Python course provided by Rice University. Recently, I was working on a mini-project involving tuples and lists. Something strange about adding a tuple to the 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 

This is pretty confusing for me. Why would a tuple indication be added using "tuple (...)" instead of just "(...)" would result in a ValueError ?

By the way: I used the CodeSkulptor coding tool used in the course

+6
source share
5 answers

The tuple function accepts only one argument, which must be iterable.

tuple([iterable])

Returns a tuple whose elements match and are in the same order as the iterable elements.

Try to make 3,4 iterable with either [3,4] (list) or (3,4) (tuple)

for instance

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

will work

+16
source

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

 a_list.append(tuple([3, 4])) 
+1
source

This has nothing to do with append . tuple(3, 4) in itself raises this error.

The reason is because, as the error message says, tuple expects an iterative argument. You can make a tuple of the contents of one object by passing this single object to the tuple. You cannot make a tuple of two things by passing them as separate arguments.

Just do (3, 4) to make a tuple, as in the first example. There is no reason not to use this simple syntax to write a tuple.

+1
source

Because tuple(3, 4) not the correct syntax for creating 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

+1
source

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 the array with parentheses

+1
source

All Articles