Python Lists

What is a Python List?

A Python list is a collection of items enclosed within square brackets ([ ]) and separated by commas. Each item in the list is called an element. Lists can hold any type of data, including numbers, strings, or even other lists.

Syntax:

list_name = [element1, element2, element3, ...]

Example:

# List of integers
numbers = [1, 2, 3, 4, 5]

# List of strings
fruits = ["apple", "banana", "cherry"]

# Mixed data types
mixed_list = [1, "hello", 3.14, True]

# Nested list
nested_list = [[1, 2], [3, 4], [5, 6]]

Characteristics of Lists

  1. Ordered:
    Elements are stored in a specific sequence, and this order is maintained.
  2. Mutable:
    Lists can be updated or modified after creation.
  3. Allow Duplicates:
    Lists can store duplicate values.
  4. Dynamic:
    The size of a list can grow or shrink as needed.

Accessing List Elements

You can access elements in a list using their index. Indexing in Python starts from 0.

Syntax:

list_name[index]

Example:

fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
print(fruits[-1]) # Output: cherry (negative index starts from the end)

Slicing Lists

Slicing allows you to extract a subset of the list.

Syntax:

list_name[start:end:step]
  • start: Starting index (inclusive).
  • end: Ending index (exclusive).
  • step: Step size (optional).

Example:

numbers = [0, 1, 2, 3, 4, 5, 6]

# Slice from index 1 to 4
print(numbers[1:5]) # Output: [1, 2, 3, 4]

# Slice with step
print(numbers[0:6:2]) # Output: [0, 2, 4]

# Slice with negative step (reverse)
print(numbers[::-1]) # Output: [6, 5, 4, 3, 2, 1, 0]

Common List Operations

1. Adding Elements

  • append(): Adds an element to the end of the list.
  • insert(): Inserts an element at a specific index.
  • extend(): Adds multiple elements to the list.
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) # Output: ['apple', 'banana', 'cherry']

fruits.insert(1, "orange")
print(fruits) # Output: ['apple', 'orange', 'banana', 'cherry']

fruits.extend(["grape", "melon"])
print(fruits) # Output: ['apple', 'orange', 'banana', 'cherry', 'grape', 'melon']

2. Removing Elements

  • remove(): Removes the first occurrence of a value.
  • pop(): Removes an element by index (default: last).
  • clear(): Removes all elements.
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits) # Output: ['apple', 'cherry']

fruits.pop(0)
print(fruits) # Output: ['cherry']

fruits.clear()
print(fruits) # Output: []

List Methods

MethodDescription
append()Adds an element to the end of the list.
insert()Inserts an element at a specified position.
extend()Adds multiple elements to the end of the list.
remove()Removes the first occurrence of a specified element.
pop()Removes an element by index or the last element.
clear()Clears all elements from the list.
index()Returns the index of the first occurrence of a value.
count()Counts the occurrences of a specified element.
sort()Sorts the list in ascending or descending order.
reverse()Reverses the order of the list.
copy()Returns a shallow copy of the list.

Iterating Through a List

You can use a for loop to iterate through the elements of a list.

Example:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

List Comprehensions

List comprehensions provide a concise way to create lists.

Syntax:

new_list = [expression for item in iterable if condition]

Example:

# Create a list of squares
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]

# Filter even numbers
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers) # Output: [0, 2, 4, 6, 8]

Nested Lists

Lists can contain other lists, enabling the creation of multi-dimensional data structures.

Example:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Accessing elements
print(matrix[0]) # Output: [1, 2, 3]
print(matrix[1][2]) # Output: 6

Leave a Comment