In Python, a List is a built-in data structure that is used to store a collection of items in a single variable. Lists are one of the most versatile and frequently used data types in Python because they can hold items of different types and are highly flexible.
Ordered: Lists maintain the order of elements. The first item has index [0], the second [1], and so on.
Changeable (Mutable): You can add, remove, or change items in a list after it has been created.
Allow Duplicates: Since lists are indexed, they can have multiple items with the same value.
Heterogeneous: A single list can contain different data types (e.g., a mix of integers, strings, and booleans).
Lists are stored as a sequence of pointers to objects in memory. This allows them to be dynamic in size, growing or shrinking as needed during the program's execution.
Lists are defined by placing elements inside square brackets [], separated by commas.
# Creating different types of lists empty_list = [] numbers = [1, 2, 3, 4, 5] mixed_list = ["Python", 2026, True, 3.14] print(f"Numbers: {numbers}") print(f"First element: {mixed_list[0]}") # Accessing by index
You can access specific parts of a list using indices or "slices."
Negative Indexing: -1 refers to the last item, -2 to the second last.
Slicing: list[start:end] returns a sub-list.
fruits = ["apple", "banana", "cherry", "orange", "kiwi"] print(fruits[1:4]) # Output: ['banana', 'cherry', 'orange'] print(fruits[-1]) # Output: 'kiwi'
Since lists are mutable, you can change specific items directly.
fruits[1] = "blackberry" print(fruits) # banana is replaced by blackberry
| Method | Description | Example |
| append() | Adds an item to the end of the list. | list.append("new") |
| insert() | Adds an item at a specific index. | list.insert(1, "item") |
| remove() | Removes a specific value. | list.remove("apple") |
| pop() | Removes the item at a given index (or last). | list.pop(0) |
| clear() | Empties the entire list. | list.clear() |
Python provides several built-in functions to handle lists efficiently:
nums = [10, 40, 20, 30, 50] # Sorting nums.sort() # Sorts list in ascending order: [10, 20, 30, 40, 50] # Reversing nums.reverse() # Reverses the order: [50, 40, 30, 20, 10] # Finding length length = len(nums) # Output: 5 # Checking existence if 20 in nums: print("20 is in the list!")
This is a powerful, "Pythonic" way to create new lists based on existing iterables in a single line.
# Syntax: [expression for item in iterable if condition] # Example: Create a list of squares for even numbers only squares = [x**2 for x in range(10) if x % 2 == 0] print(squares) # Output: [0, 4, 16, 36, 64]
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION