This question already has answers here:
Why does substring slicing with index out of range work?
(3 answers)
Closed 9 years ago.
While this code will raise indexError:
In [1]: lst = [1, 2, 3]
In [2]: lst[3]
IndexError: list index out of range
Slicing the list with "out of range index" will not produce any error.
In [3]: lst[3:]
Out[3]: []
What is the rationale of this design?
When you are accessing an element in a list whose index is beyond its length, we cannot return anything. (There is no way we can represent an element which is not there). That's why the error is thrown. But when you are slicing, you are making a sliced COPY of the original list and that new list can be empty if the start or end are not valid.
It's nice being able to test if an element exists:
if sys.argv[2:]:
# do something with sys.argv[2], knowing it exists
Related
This question already has answers here:
Why does substring slicing with index out of range work?
(3 answers)
Python index out of range in list slicing [duplicate]
(2 answers)
Why does assigning past the end of a list via a slice not raise an IndexError? [duplicate]
(2 answers)
Closed 2 years ago.
Given the expressions:
>>> l = [1,2,3]
>>> l[10:20] = [4,5]
>>> l
[1, 2, 3, 4, 5]
Why doesn't Python nag about the nonexistent items meant to be deleted? l.remove(55) does raise a ValueError.
l.remove(55) Raises an error because you don't have the value 55 in your list.
On the other hand, l[10:20] = [4,5] is not crashing your code because that slicing method will try to add elements on those indexes, if it can't, it will be adding the new elements in the last position of your array.
Also, if you try to do (for example) l[10]=10, this will Raise the exception: IndexError: list index out of range
This question already has answers here:
Understanding slicing
(38 answers)
Closed 6 years ago.
Suppose I was slicing a list and a string:
num_list = [1, 2, 3, 4]
print(num_list[2:]) # => [3, 4]
text_string = 'This is a test string'
print(text_string[5:] # => 'is a text string'
So, when I slice the list, the first slice index is inclusive, but when I slice the string, the slice index is noninclusive. What is it like this? Why does string slicing not follow the same ruleset that list slicing appears too?
My understanding of list slicing is that the left slice index is always inclusive, whilst the right slice index is only inclusive when it is left blank.
They both behave exactly the same.
For some reason you expect the list's indexes to start from 0 and
the string's indexes to start from 1.
The fact is that they both start at 0.
As #Mark suggested in the comments, strings and lists indexing from Python's documentation.
But it is the same!
Insert indices before each element:
[0=1,1=2,2=3,3=4][2:] means: from index 2 until end
[0=T,1=h,2=i,3=s,4= ,5=i,6=s,...][5:] means: from index 5( in this case from the letter 'i') until the end.
This question already has answers here:
Understanding slicing
(38 answers)
Closed 6 years ago.
I'm a beginner attempting to learn Python. I am familiarising myself with the list data type; I've defined the following list:
>>> numbers = [1, 2, 3, 4]
Typing:
>>> numbers[0]
1
>>> numbers[1]
2
>>> numbers[2]
3
>>> numbers[3]
4
Given this, why do I get the following when I attempt to retrieve the following list elements:
>>> numbers[0:3]
[1, 2, 3]
Why isn't the list element '4' included in the response from the interpreter?
Thank you for your help.
Slice notation does not include the last element (similar to the range() function in that respect). If you want to include the last element, simply omit an index. Also, the default start is the beginning, so you don't need 0 there either:
>>> numbers[:]
[1, 2, 3, 4]
Note that this is a (shallow) copy of numbers. If you save a reference to it, you can mutate it without affecting the original numbers.
That's how slicing works in Python. To quote a tutorial:
Note how the start is always included, and the end always excluded.
This makes sure that s[:i] + s[i:] is always equal to s.
The example uses a string, but slicing works the same way with lists.
numbers[0:3] list from 0 up to 3 but 3 is excluded (like range(0,3))
This question already has answers here:
Deleting multiple elements from a list
(32 answers)
Closed 7 years ago.
I have an index of list elements that I want to delete. How can I do that ?
For example, if my original list is a=[1,2,3,4,5,6] and my index list is [2,3]. I want the elements 3,4 to be removed
Since you want to delete the indices, you can do the following two methods:
In place:
for index in sorted(indices, reversed=True):
del a[index]
out of place:
new_a = [el for index, el in enumerate(a) if index not in indices]
The reason why we sort for the in-place version is because deleting from the back doesn't modify the referenced elements in the front (note that this breaks with negative indexing).
a=[1,2,3,4,5,6]
a = a[:2] + a[4:]
print(a)
[1, 2, 5, 6]
This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 9 years ago.
I need to access the n and n+1 elements of a list. For example, if my list was [1,2,3,4,5] and my nth element was 2, I'd need the next element in the list, 3.
Specifically, I need to access these elements in order to use them to look up a value in a matrix A
I have a for loop that's iterating over the list:
list = [1,2,3,4,5]
for i in list:
value = A[i,i+1] #access A[1,2], A[2,3], A[3,4], A[4,5]
the problem with this is that I can't do an i+1 operation to access the n+1 element of my list. This is my first time programming in Python and I assumed element access would be the same as in C/C++ but it's not. Any help would be appreciated.
You can use slicing operator like this
A = [1, 2, 3, 4, 5]
for i in range(len(A) - 1):
value = A[i:i+2]
The range function lets you iterate len(A) - 1 times.
Enumerate can give you access to the index of each item:
for i, _ in enumerate(A[:-1]):
value = A[i:i+2]
If all you need are the pairs of data:
for value in zip(A, A[1:]):
value