Lists Slicing in Python.


LIST SLICING:

You saw that we can pull more than one value from a list at a time by using slicing. When using slicing, it is important to remember that the lower index is inclusive and the upper index is exclusive.

Therefore, this:

>>> list_of_random_types = [1, 3.4, 'a string', True]
>>> list_of_random_types[1:2]



will only return 3.4 in a list. Notice this is still different than just indexing a single element because you get a list back with this indexing. The colon tells us to go from the starting value on the left of the colon up to, but not including, the element on the right.

If you know that you want to start at the beginning, of the list you can also leave out this value.

>>> list_of_random_things[:2]


or to return all of the elements to the end of the list, we can leave off a final element.

>>> list_of_random_things[1:]



This type of indexing works exactly the same on strings, where the returned value will be a string.

Are you in OR not in?

You saw that we can also use in and not in to return a bool of whether an element exists within our list, or if one string is a substring of another.

>>> 'this' in 'this is a string'

True

>>> 'in' in 'this is a string'

True

>>> 'isa' in 'this is a string'

False

>>> 5 not in [1, 2, 3, 4, 6]

True

>>> 5 in [1, 2, 3, 4, 6]

False


Post a Comment

0 Comments