List Slicing Lesson for Python

I’d like to understand further how the brackets are working in the piece of code. What are they telling the program to do? Why does the colon go in front of one number but behind the next? And why is four acceptable in the last, when it is in index position 3?

first_4_fb = row_1[:4]
last_3_fb = row_1[-3:]
pandora_3_4 = row_5[2:4]

1 Like

Hi @jmhenderson10111,

Python has 0-based index. It means that in a Python list, for example, the 1st item has the index 0, the 2nd item has the index 1, etc. You can index a list also from the end, then the first item on the right end will have the index -1, the second to the last - index -2, etc. In list slicing, the number means the index of an item (always remembering that in Python the indexing starts with 0). If the colon goes before the number, it means that you extract all the items from the list up to but not including the index expressed by that number. If the colon goes after the number, it means that you extract all the items from the list starting from and including the index expressed by that number. If the colon separates two numbers (i.e., 2 indices), it just means that the first index will be included and the second one will not be included.

And why is four acceptable in the last, when it is in index position 3?

The item with the index 4 will not be included here. Only the items with the indices 2 and 3.

1 Like