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)]
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.
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.
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.
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]))
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With