Loading lesson...
Slice, combine, and organize your data
Slice, combine, and organize your data
Topics covered: List Slicing, Combining Lists, Sorting Lists, Reversing Lists, Searching in Lists
Why Exclude the End Index? The two halves split cleanly at index 4. No item appears in both halves, and no item is missing. The combined length equals the original length. This clean division is possible because the end of one slice equals the start of the next. Omitting Start or End You can omit the start index, the end index, or both. Omitting start means "from the beginning." Omitting end means "to the end." This gives you convenient shortcuts for common operations. Negative Indices in Slices
The extend() Method extend() vs append() Choosing the wrong method when combining lists is one of the most frequent sources of nested-list bugs. Keep these rules in mind as you work with multi-source data. extend() with Any Iterable Notice what happened with the string "cd": each character became a separate item in the list. This is because strings are iterable, and iterating over a string yields individual characters. This behavior can be surprising if you expected the whole string to be added
The sort() Method Numbers are sorted from smallest to largest. Strings are sorted alphabetically based on Unicode code points, which means uppercase letters come before lowercase letters in a pure ASCII comparison. The original lists are modified directly. The sorted() Function The original list remains [3, 1, 4, 1, 5, 9, 2, 6] after calling sorted(). The sorted_copy is a new list containing the same values in sorted order. Notice that sorted() can work on strings too, returning a list of sorted
The reverse() Method The reversed() Function Slice Reversal
Beyond checking if an item exists with the "in" operator (covered in the beginner lesson), Python provides methods to find where items are located and how many times they appear. These are essential for data analysis and processing. The index() Method Search from Any Position By starting the search at different positions, we can find each successive occurrence of the value 10. This is useful when you need to process all occurrences of a value. Handling Not Found Errors The count() Method Finding