Concept: List methods & operators
A list contains multiple methods that can be used to manipulate the list. Some of the most commonly used methods are:
append(): Adds an item to the end of the list.users = ["Alice", "Bob"] users.append("Eve") print(users) # Output: ["Alice", "Bob", "Eve"]extend(): Extends the list by appending all the items from another iterable (e.g., another list).users = ["Alice", "Bob"] new_users = ["Eve", "Frank"] users.extend(new_users) print(users) # Output: ["Alice", "Bob", "Eve", "Frank"]insert(): Inserts an item at a specified index in the list.users = ["Alice", "Bob"] users.insert(1, "Eve") print(users) # Output: ["Alice", "Eve", "Bob"]remove(): Removes the first occurrence of a specified item from the list.users = ["Alice", "Bob", "Eve"] users.remove("Eve") print(users) # Output: ["Alice", "Bob"]pop(): Removes and returns the item at a specified index (or the last item if no index is specified).users = ["Alice", "Bob", "Eve"] removed_user = users.pop(1) print(users) # Output: ["Alice", "Eve"] print(removed_user) # Output: "Bob"clear(): Removes all items from the list.users = ["Alice", "Bob", "Eve"] users.clear() print(users) # Output: []len(): Returns the number of items in the list.users = ["Alice", "Bob", "Eve"] length = len(users) print(length) # Output: 3index(): Returns the index of the first occurrence of a specified item in the list.users = ["Alice", "Bob", "Eve"] index_eve = users.index("Eve") print(index_eve) # Output: 2reverse(): Reverses the order of items in the list.users = ["Alice", "Bob", "Eve"] users.reverse() print(users) # Output: ["Eve", "Bob", "Alice"]count(): Returns the number of occurrences of a specified item in the list.users = ["Alice", "Bob", "Eve", "Alice"] count_alice = users.count("Alice") print(count_alice) # Output: 2
There are also operators that can be used with lists:
| Operator | Description | Example | Result |
|---|---|---|---|
+ | Concatenation | ["a", "b"] + ["c", "d"] | ["a", "b", "c", "d"] |
* | Repetition | ["a", "b"] * 2 | ["a", "b", "a", "b"] |
< | Less than | ["a", "b"] < ["c", "d"] | True |
> | Greater than | ["a", "b"] > ["c", "d"] | False |
== | Equal to | ["a", "b"] == ["a", "b"] | True |
!= | Not equal to | ["a", "b"] != ["c", "d"] | True |
in | Membership | "a" in ["a", "b"] | True |
not in | Not membership | "c" not in ["a", "b"] | True |