Python Forum
TypeError indexing a range of elements directly on the list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
TypeError indexing a range of elements directly on the list
#1
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
Reply
#2
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.
Reply
#3
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]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 418 Jan-27-2024, 04:03 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 462 Oct-17-2023, 09:46 AM
Last Post: tomciodev
Thumbs Down I hate "List index out of range" Melen 20 3,298 May-14-2023, 06:43 AM
Last Post: deanhystad
  Checking if a string contains all or any elements of a list k1llcod3 1 1,085 Jan-29-2023, 04:34 AM
Last Post: deanhystad
  Import XML file directly into Excel spreadsheet demdej 0 833 Jan-24-2023, 02:48 PM
Last Post: demdej
  How to change the datatype of list elements? mHosseinDS86 9 1,952 Aug-24-2022, 05:26 PM
Last Post: deanhystad
  IndexError: list index out of range dolac 4 1,897 Jul-25-2022, 03:42 PM
Last Post: deanhystad
  TypeError: float() argument must be a string or a number, not 'list' Anldra12 2 4,846 Jul-01-2022, 01:23 PM
Last Post: deanhystad
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 5,104 May-17-2022, 11:38 AM
Last Post: Larz60+
  TypeError: unsupported opperand type(s) for %: 'int' and 'list' cool_person 7 2,139 May-07-2022, 08:40 AM
Last Post: ibreeden

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020