Meaning of square brackets

HI I wonder if any one can help me understanding the use of the square brackets on the end of this statement.
mail_ids = mails[0].decode().split()[-2:]
How does the [-2:] work?
thanks
dazza000

Ok, I think I have got it now. it is about the indexing of a list. I think it is referring to the last two elements of the list called mails.

mails[0].decode() probably returns a string.

mails[0].decode().split() probably splits that string into a list of substrings.

mails[0].decode().split()[-2:] gives you the sub-list of the last two items from that list.

For example:

>>> L = "My hovercraft is full of eels.".split()
>>> L[-2:]
['of', 'eels.']

This is called “slicing”.

2 Likes

The first thing to understand is that the output from split() is a list. See the documentation for str.split(). A list is a sequence type.

The second thing to understand is the meaning of square brackets after a sequence type is a slice. The meaning is defined in the Python Library Reference, section Common Sequence Operations. See especially note (4) after the table.

I encourage you to read and re-read the Python Documentation, https://docs.python.org/3/. I have been programming in Python for many years, and I still refer back to the documentation all. the. time. It is really helpful.

That is just guessing. split() is a method here. You do not know if it is being called on a str object in the code. That is why Steven used the word “probably”: