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 We can access elements using indexing (starting at 0 for the first element).

Python

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

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