![]() |
TypeError indexing a range of elements directly on the list - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: TypeError indexing a range of elements directly on the list (/thread-25441.html) |
TypeError indexing a range of elements directly on the list - JFerreira - Mar-30-2020 Hi, I am getting an TypeError, and not sure why? My goal is to write on the second and third position of a list . I can do it using a for loop but I would like to avoid the for loop by indexing a range of elements directly on the list. How can I do it? >>>list=[1,3,4,30,10,20] >>>for i in range(1,3,1): list[i] = 0 >>>list [1, 0, 0, 30, 10, 20] >>>list[1:3] = 1 Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: can only assign an iterable RE: TypeError indexing a range of elements directly on the list - stullis - Mar-30-2020 Hmm, I never thought to even try that. The problem is that list[1:3] selects values from index 1 up to index 3 for a total of 2 items. You cannot replace multiple items with a single item. Instead, you need to provide an interable for the interpreter to loop over and replace values. list[1:3] = [1]While we're at it, it's inadvisable to use "list" as a variable name. Think of it like a reserved keyword because there's a builtin function called list() and Python replaces it with the variable. RE: TypeError indexing a range of elements directly on the list - bowlofred - Mar-30-2020 If you want to replace both items with "1",s then something like this: >>> l = [1,3,4,30,10,20] >>> l [1, 3, 4, 30, 10, 20] >>> l[1:3] = [1] * 2 >>> l [1, 1, 1, 30, 10, 20] |