Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending tuples to lists

What's the proper syntax for adding a recomposed tuple to a list?

For example, if I had two lists:

>>> a = [(1,2,3),(4,5,6)]
>>> b = [(0,0)]

Then I would expect the following to work:

>>> b.append((a[0][0],a[0,2]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple

Furthermore, when it informs me that indices must be integers, how come this works?

>>> b.append((7,7))
>>> b
[(0, 0), (7, 7)]
like image 564
Unreason Avatar asked Nov 08 '10 17:11

Unreason


People also ask

Can we append in list of tuple in Python?

Adding/Inserting items in a Tuple You can concatenate a tuple by adding new items to the beginning or end as previously mentioned; but, if you wish to insert a new item at any location, you must convert the tuple to a list.

Can you use += for tuples?

Why do Python lists let you += a tuple, when you can't + a tuple? In other words: No. Trying to add a list and a tuple, even if we're not affecting either, results in the above error. That's right: Adding a list to a tuple with + doesn't work.

How do you turn a tuple into a list?

tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.


2 Answers

you have try to do this:

(a[0][0],a[0,2])
           ^^^

this is like doing:

(a[0][0],a[(0,2)])

which like the error said : list indices must be integers, not tuple

if i'm not mistaken, i think you wanted to do:

b.append((a[0][0],a[0][2]))
like image 75
mouad Avatar answered Sep 23 '22 14:09

mouad


Your problem is this:

b.append((a[0][0],a[0,2]))
                     ^

You try to use the nonexistent tuple index [0, 2] when you mean [0][2]

like image 35
Rafe Kettler Avatar answered Sep 23 '22 14:09

Rafe Kettler