Python list slices | Sololearn: Learn to code for FREE!


Python list slices

squares = [0,1,4,9,16,25,36,49,64,81] this is the list print(squares[0:-1]) Shouldn't it print all of the values of the list but instead it printed 0 to 64. Can anyone help?

4/16/2021 3:13:39 PM


4 Answers

New Answer


squares[0:-1] In words, from first element up to second last element. Remember, negative indexing gets the element from right. So for example list[-1] will get the last element, list[-2] will get the second last element and so on.. But in index slicing, remember that the second or the `stop` index is excluded. Example: lst = [42, 34, 12, 56] print(lst[0:3]) Now let us first enumerate each elements with their indexes. lst[0] --> 42 lst[1] --> 32 lst[2] --> 12 lst[3] --> 56 Therefore lst[0:3] will get indexes 0, 1 and 2 exluding index 3. Output: [42, 34, 12]


Thanks but if the list is big and i cant be bothered to count until the end of the list's index, how will i go about that?


FADE If you want to get the last element of the list even without knowing the number of elements, you can use negative indexing. Or you can also find first the number of elements from the list using the len function. len(list) Then you can use that as an index (but make sure to subtract number from it to avoid IndexError because indexing starts from 0) Examples of getting the last two elements: iterable[-2] iterable[len(iterable) - 2] Not sure if I understand your question correctly so please ask again if this is not what youre asking for. Thanks.


FADE This was my comment on the lesson of List Slices on "Python for Beginners" course. I couldn't copy the lesson's link so I'll just copy the whole text here, maybe this could help. ____________________________ Index Slicing Arguments: --> list [ start : end : step ] Default Values: --> start = 0 --> end = length of the string --> step = 1 We can also set or assign values to one or multiple elments using index slicing: _______________________________ Additional: You can omit either the first or second index, it will use the default value. For example: list[0:3] is also list[ :3] And if you want to slice for example from index 3 up to the last element. list[3: ]