Append and Insert
Python offers two primary methods for adding elements to a list:append and insert.
- The
appendmethod adds a new element to the end of the list. - The
insertmethod places a new element at a specific index, shifting the current and subsequent items to the right.
Ensure that you choose between
append and insert based on whether the element’s position matters in your program.Swapping Values in a List
Swapping values in a list can be handled in a couple of different ways. One conventional method involves using a temporary variable:Sorting and Reversing Lists
Two additional valuable methods for handling lists aresort and reverse.
-
The
sortmethod arranges the elements of the list in ascending order. This applies to both numeric (from lowest to highest) and string (alphabetical) data. Note that the original list is updated, and no new sorted list is returned. For example: -
The
reversemethod inverts the order of the list elements, making the first element last and vice versa. Here’s how you can use it:
reverse method flips the order of elements relative to their original sequence.
Summary
| Method | Purpose | Example |
|---|---|---|
| append | Adds an element to the end of the list. | countries.append(“Spain”) |
| insert | Adds an element at a specified index. | countries.insert(2, “Italy”) |
| sort | Sorts the list in ascending order. | ages.sort() |
| reverse | Reverses the order of the list elements. | ages.reverse() |