Topic 1: Lists: Operations and Methods

1. Introduction

A list is a mutable, ordered collection of items in Python. Each item inside a list is referred to as an element. Since lists are mutable, their contents can be modified after creation.

2. Creating Lists

You can create lists using square brackets [] and separating items with commas.

python
fruits = ["apple", "banana", "cherry"]

3. Accessing Elements

Elements can be accessed by their index.

python
print(fruits[0]) # Outputs: apple

4. Basic Operations

  • Length: Find the number of items in a list.
python
print(len(fruits)) # Outputs: 3
  • Concatenation: Combine two lists.
python
vegetables = ["carrot", "broccoli"] food = fruits + vegetables print(food) # Outputs: ['apple', 'banana', 'cherry', 'carrot', 'broccoli']
  • Repetition: Repeat a list.
python
print(fruits * 2) # Outputs: ['apple', 'banana', 'cherry', 'apple', 'banana', 'cherry']
  • Membership: Check if an item exists in a list.
python
print("apple" in fruits) # Outputs: True

5. List Methods

  • append(): Add an element to the end of the list.
python
fruits.append("grape") print(fruits) # Outputs: ['apple', 'banana', 'cherry', 'grape']
  • extend(): Extend a list with another list or iterable.
python
fruits.extend(["mango", "pineapple"]) print(fruits) # Outputs: ['apple', 'banana', 'cherry', 'grape', 'mango', 'pineapple']
  • insert(): Insert an element at a specific position.
python
fruits.insert(1, "orange") # Insert "orange" at the second position print(fruits) # Outputs: ['apple', 'orange', 'banana', 'cherry', 'grape', 'mango', 'pineapple']
  • remove(): Remove the first occurrence of a specific value.
python
fruits.remove("banana") print(fruits) # Outputs: ['apple', 'orange', 'cherry', 'grape', 'mango', 'pineapple']
  • pop(): Remove an element by index and return it. If no index is provided, it removes the last item.
python
removed_fruit = fruits.pop(0) print(removed_fruit) # Outputs: apple print(fruits) # Outputs: ['orange', 'cherry', 'grape', 'mango', 'pineapple']
  • index(): Return the index of the first occurrence of a value.
python
position = fruits.index("cherry") print(position) # Outputs: 1
  • count(): Count the occurrences of a value in the list.
python
num_cherries = fruits.count("cherry") print(num_cherries) # Outputs: 1
  • sort(): Sort the list in-place.
python
fruits.sort() print(fruits) # Outputs: ['cherry', 'grape', 'mango', 'orange', 'pineapple']
  • reverse(): Reverse the list in-place.
python
fruits.reverse() print(fruits) # Outputs: ['pineapple', 'orange', 'mango', 'grape', 'cherry']
  • clear(): Remove all elements from the list.
python
fruits.clear() print(fruits) # Outputs: []

6. Conclusion

Lists are one of Python’s most versatile and commonly used data structures. Understanding the operations and methods associated with lists provides a robust foundation for tackling more complex problems and data manipulations in Python.