<jupyter_start><jupyter_text>Slicing in PythonPython allows slicing a collection into a smaller subset Let's first create a list<jupyter_code>l = [1, 2, 3, 4, 5, 6, 7, 8 ,9 ,10]<jupyter_output><empty_output><jupyter_text>Let's say I wanted to get only the first four elements of the list. How do we do that?You can slice a list by specifying the starting index and ending index in the square brackets, separated by a ```:```<jupyter_code>first_four = l[0: 4]
print first_four<jupyter_output>[1, 2, 3, 4]<jupyter_text>What if we wanted to get all the elements except the first one?If you don't specify anything after the ```:```, python will get everything till the end of the list<jupyter_code>second_to_last = l[1:]
print second_to_last<jupyter_output>[2, 3, 4, 5, 6, 7, 8, 9, 10]<jupyter_text>What if you wanted only the last two elements?__Hint__: Use the -ve indices :)<jupyter_code>print l[-2:]<jupyter_output>[9, 10]<jupyter_text>Exercise* How will you get values from 2nd position till the second last potion in the list?* How will you get the seonc last and thir last values?  Slicing TuplesSlicing tuples is exactly similar to lists and left as an exercise for you to try out  Slicing StringsStrings are very similar to lists, they are an ordered sequence of characters and thus they can also be sliced and diced<jupyter_code>name = '<NAME>'
print name<jupyter_output><NAME><jupyter_text>Indexing in strings is same as lists or tuples<jupyter_code>print name[0]
print name[-1]
print name[2]<jupyter_output>B
r
b<jupyter_text>Slicing strings is the way to do substring operations in python<jupyter_code>print name[0:3]
print name[4:7]
print name [-7: ]<jupyter_output>Builder
{'fraction_non_alphanumeric': 0.0855614973262032, 'fraction_numerical': 0.0243612596553773, 'mean_word_length': 6.016666666666667, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '114558', 'license': 'BSD-2-Clause', 'n_tokens_mistral': 597, 'n_tokens_neox': 559, 'n_words': 228, 'path': 'notebooks/Slicing in Python.ipynb', 'repo_name': 'abhinav-upadhyay/intro-to-python', 'size': '1701'}