<jupyter_start><jupyter_text>Cropping listsA common task in Python is to crop out parts of lists and tuples, for example to access specific parts from lists.Let's start with a list of numbers<jupyter_code>data = [34, 0, 65, 23, 51, 9, 50, 78, 34, 100]<jupyter_output><empty_output><jupyter_text>We can determine how many elements are in `data`:<jupyter_code>len(data)<jupyter_output><empty_output><jupyter_text>As shown earlier, we can access specific elements by passing an index. Counting the element-index starts at 0.<jupyter_code>data[0]
data[1]<jupyter_output><empty_output><jupyter_text>We can also pass negative indices. This will access elements from the end of the list. The last element has index -1.<jupyter_code>data[-1]
data[-2]<jupyter_output><empty_output><jupyter_text>Selecting ranges in listsWe can also generate a new list that contains the first three elements. Therefore, we pass a range in form `[start:end]`. The first element has index `start` and the last element of the new list will be just before `end`.<jupyter_code>data
data[0:2]
data[0:3]
data[1:2]<jupyter_output><empty_output><jupyter_text>Furthermore, we don't have to specify either `start` or `end` if we want to select all entries in a list from the start or until the end.<jupyter_code>data
data[:2]
data[:3]
data[2:]
data[3:]<jupyter_output><empty_output><jupyter_text>This also works with negative indices<jupyter_code>data[-2:]<jupyter_output><empty_output><jupyter_text>Stepping over entries in listsThe `:` can also be used to provide a step length using the syntax `[start:end:step]`.<jupyter_code>data<jupyter_output><empty_output><jupyter_text>For example we can select every seceond element starting at the first:<jupyter_code>data[0:10:2]
data[::2]<jupyter_output><empty_output><jupyter_text>We can also start at the second element (index 1):<jupyter_code>data[1::2]<jupyter_output><empty_output><jupyter_text>TuplesAll the introduced concepts above also work with tuples<jupyter_code>immutable_data = tuple(data)
immutable_data
immutable_data[:5]<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.098747591522158, 'fraction_numerical': 0.02167630057803468, 'mean_word_length': 7.8382978723404255, 'pattern_counts': {'":': 0, '<': 45, '<?xml version=': 0, '>': 45, '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': '11', 'dir': 'jupyter-structured-clean-dedup', 'id': '177495', 'license': 'CC-BY-4.0', 'n_tokens_mistral': 724, 'n_tokens_neox': 695, 'n_words': 216, 'path': 'docs/02_python_basics/05a_cropping_lists.ipynb', 'repo_name': 'rayanirban/BioImageAnalysisNotebooks', 'size': '2076'}