TypeError: can only assign an iterable | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

TypeError: can only assign an iterable

https://code.sololearn.com/c01Gmd0PTrEw/?ref=app I am novice programmer. I decided to experiment with the code and stumbled upon this error. Nothing is clear on the Internet, something about RHS. Please tell me in more details what it is.

12th Jun 2023, 12:36 PM
garfy
4 Answers
+ 6
garfy , the solution is rather simple. we can use: ... letters[:3]= [5] # uses an iterable to replacd index 0 upto and including index 2 the output will be: [5, 'd', 'e', 'f', 'g'] > instead of using [5], we can also use a variable like *num*, that contains a number like 5: letters[:3] = [num] > the slice assignment with an iterable can be also done also like: letters[:3]= 5, # by using this notation (note the *comma* after the 5), a tuple with the element of 5 is created and assigned to the list
12th Jun 2023, 1:02 PM
Lothar
Lothar - avatar
+ 2
thank you so much!
12th Jun 2023, 1:31 PM
garfy
+ 1
You need to assign some iterables like list, tuple in RHS since you are using slicing. Iterables means any object (note: list is object. for more information you can google Object oriented programming) that can be iterate over. Iterate mean executing block of code again and again you can do something like letters[:3] = [1,2,3] or you can use tuple,dictionary or any iterables insted of list
12th Jun 2023, 12:51 PM
Bishnu Chalise
Bishnu Chalise - avatar
+ 1
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] # you first created a list here letters[:3]= 5 # Error # this letters[:3] is selecting the first 3 elements of the list and the next part, = 5 is trying to replace the 3 elements of the list with 5 # but here 5 is an integer and letter[:3] is a list with 3 items, you can't replace a list with an integer #use letter[:3] = [5] to avoid error, as both are lists now print(letters) By the way, letter[:3] and letter[3] are never same.
12th Jun 2023, 12:54 PM
I-M-J
I-M-J - avatar