This section covers the core concepts of Python, including language fundamentals, built-in data types, and variables. Understanding these basics is crucial for anyone looking to build a solid foundation in Python programming.
9 audio · 2:15
Nortren·
What is slicing in Python?
0:16
Slicing is the operation of extracting a subsequence from a sequence using square brackets and a start, stop, and step. The general form is sequence with brackets containing start colon stop colon step. The result is a new sequence containing elements from start up to but not including stop, taking every step element.
Negative indices count from the end of the sequence backward. Index negative one is the last element, negative two the second to last, and so on. Negative indices work in slicing too, allowing you to express slices relative to the end without computing the length.
To reverse a sequence, use a slice with a step of negative one and no start or stop. For a list named items, items with brackets containing colon colon negative one returns a new list with elements in reverse order. This is concise but creates a copy. For in-place reversal, use the reverse method.
The sort method is defined on lists and sorts the list in place, returning None. The sorted built-in function takes any iterable and returns a new sorted list, leaving the original unchanged. Both accept a key function and a reverse flag.
The key parameter accepts a function that is called on each element to compute a sort key. Sorting then compares the keys instead of the elements directly. For example, sorting a list of strings by length uses key equals len. The original elements are returned in the order determined by their keys.
Timsort is the sorting algorithm used by Python for sort and sorted. It is a hybrid of merge sort and insertion sort designed to perform well on real-world data with existing order. It is stable, has a worst case time complexity of n log n, and a best case of linear time on already sorted data.
A list comprehension is a concise way to create a list by applying an expression to each element of an iterable, optionally filtered by a condition. The syntax is brackets containing expression for variable in iterable optionally followed by if condition. They are typically faster and more readable than equivalent for loops with append.
Dictionary comprehensions use curly braces with key-colon-value pairs to build a dictionary in one expression. Set comprehensions use curly braces without colons to build a set. Both follow the same pattern as list comprehensions but with different brackets and resulting types.
A generator expression looks like a list comprehension but uses parentheses instead of square brackets. It returns a generator object that produces values lazily, one at a time, instead of building a full list in memory. This is efficient for large datasets or infinite sequences.
---