Problem slicing a list with the C API
Chris Angelico
rosuav at gmail.com
Sat Mar 12 18:36:02 EST 2022
On Sun, 13 Mar 2022 at 10:30, Jen Kris <jenkris at tutanota.com> wrote:
>
>
> Chris, you were right to focus on the list pDictData itself. As I said, that is a list of 2-tuples, but I added each of the 2-tuples with PyList_Append, but you can only append a tuple to a list with the extend method. However, there is no append method in the C API as far as I can tell -- hence pDictData is empty. I tried with PyList_SetItem but that doesn't work. Do you know of way to "extend" a list in the C API.
>
Hmm. Not entirely sure I understand the question.
In Python, a list has an append method, which takes any object (which
may be a tuple) and adds that object to the end of the list:
>>> x = ["spam", "ham"]
>>> x.append((1,2))
>>> x
['spam', 'ham', (1, 2)]
A list also has an extend method, which takes any sequence (that also
includes tuples), and adds *the elements from it* to the end of the
list:
>>> x = ["spam", "ham"]
>>> x.extend((1,2))
>>> x
['spam', 'ham', 1, 2]
The append method corresponds to PyList_Append, as you mentioned. It
should be quite happy to append a tuple, and will add the tuple
itself, not the contents of it. So when you iterate over the list,
you'll get tuples.
Extending a list can be done with the sequence API. In Python, you can
write extend() as +=, indicating that you're adding something onto the
end:
>>> x = ["spam", "ham"]
>>> x += (1, 2)
>>> x
['spam', 'ham', 1, 2]
This corresponds to PySequence_InPlaceConcat, so if that's the
behaviour you want, that would be the easiest way to do it.
Based on your other comments, I would suspect that appending the
tuples is probably what you want here?
ChrisA
More information about the Python-list
mailing list