List in Python

In Python, a list is a collection data type that is mutable, ordered, and allows duplicate elements. Lists are commonly used to store multiple items in a single variable. Here's an explanation of its key features and how to work with lists:

Key Features

  1. Ordered: The elements in a list have a defined order, which will not change unless explicitly modified.
  2. Mutable: You can change the content of a list after it is created (e.g., add, remove, or modify elements).
  3. Allows Duplicates: A list can contain duplicate elements.
  4. Dynamic: Lists can grow or shrink in size, and they can hold elements of different data types.

Creating a List A list is created using square brackets [].

Python

# Empty list
my_list = []

# List with elements
fruits = ['apple', 'banana', 'cherry']

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

Accessing Elements in a list We can access list elements using indexing.

Python

fruits = ['apple', 'banana', 'cherry']

# Accessing elements
print(fruits[0])  # Output: apple
print(fruits[-1])  # Output: cherry (negative indexing starts from the end) 

Iterate over List Items Iteration means going through each element of a list one by one.

Python

numbers = [10, 20, 30, 40]

# Iterate
for num in numbers:
    print(num) 

Output 10
20
30
40

del keyword with List in Python We can use the del keyword to delete one or more elements from a list.

Example: Delete a Single Item (by index).

Python

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

# Delete item at index 1
del fruits[1]

print(fruits)   # ['apple', 'cherry', 'mango']