+ 3
List slice problem in python
Can anybody tell why print(s) is perfectly working while print(n) is giving error? s = ['a','b'] s[1:1] = 'c' print(c) #not error n = [1,2] n[1:1] = 3 print(n) #error https://code.sololearn.com/cfHG6j65e08o/?ref=app
5 Respostas
+ 6
s = ['a','b']
s[1:1] = 'c'
print(c) # actually, this would be an error because c is undefined. I think you want s.
That's just a typo from you I'm sure, though.
The answer to your main question is that a number is not iterable.
A string is. You can iterate through characters of a string.
Check this out:
>>> n = [1,2]
>>> n[1:1] = 'hello'
>>> print(n)
[1, 'h', 'e', 'l', 'l', 'o', 2]
>>>
See how the assignment iterates over characters in the string? That's what it can not do with a number. Assigning individual characters earlier was misleading you into ignoring the iteration.
Also, check out this:
>>> n = [1,2]
>>> n[1:1] = [3] # a list is iterable so this will not lead to an error.
>>> print(n)
[1, 3, 2]
>>>
A generator is also iterable and the range function is a generator:
>>> n = [1,2]
>>> n[1:1] = range(4)
>>> print(n)
[1, 0, 1, 2, 3, 2]
>>>
+ 2
Mir wrote, "Ok thanks I got it. I need an iterable cause if i did n[1:6] then an integer would unable to divide itself in 5 parts and put it into those slices. That's why creators of python allowed only iterables to be used in s[x:y] slices. Is that correct?"
Response:
I didn't design Python so I can only speculate why they did this so I'll speculate now.
n[1:6] is an iterable. More precisely it returns a list.
It would be weird if you could assign a value of one type and have it turn into something else. That's why you need to explicitly convert data types with things like the str function, int function...
The operation is basically to replace the index range within a list with a number of other elements. These other elements can be empty or contain as many elements as can fit in memory. This means that through assigning, you can remove elements at any range, replace them, or insert more.
The number of elements being iterated doesn't need to match anything about the index range you're replacing or inserting to.
n = [1, 2]
n[0:2] = []
Now, n will be empty because the entire range of the list was replaced with nothing.
+ 1
n[1:1] = '3' should solve your problem.
0
Ok thanks I got it. I need an iterable cause if i did n[1:6] then an integer would unable to divide itself in 5 parts and put it into those slices. That's why creators of python allowed only iterables to be used in s[x:y] slices. Is that correct?
0
Good point and make sense. Thanks for the response.