List in Python – Types, Examples, and Complete Overview
A list in Python is a built-in data structure used to store multiple values in a single variable. Lists are ordered, mutable (changeable), and allow duplicate values, making them one of the most commonly used data types in Python.
Why It Matters: Lists help manage and manipulate collections of data efficiently in real-world Python programs.
Creating a List in Python
Lists in Python are created using square brackets []. They can store elements of the same or different data types.
Examples include numeric lists, string lists, and mixed-type lists.
Types of Lists in Python
Python does not define separate list types, but lists are commonly categorized based on how they are used.
- Simple List: Stores elements of the same data type
- Mixed List: Stores elements of different data types
- Nested List: A list inside another list
- Empty List: A list with no elements
Accessing and Slicing List Elements
List elements are accessed using indexing, which starts from 0. Negative indexing allows access from the end of the list.
Slicing helps extract a portion of a list using a range of indexes.
Modifying and Managing Lists
Lists are mutable, meaning their elements can be changed after creation. Python provides many built-in methods to add or remove elements.
- Adding elements using append(), insert(), and extend()
- Removing elements using remove(), pop(), and del
- Sorting and reversing lists
Looping and List Comprehension
Python allows easy iteration over lists using loops. List comprehension provides a concise and powerful way to create new lists.
List comprehensions improve readability and reduce the number of lines of code.
Advantages, Disadvantages, and Real-World Use
Lists are flexible and powerful but may not be ideal for every situation.
- Easy to store and modify multiple values
- Dynamic size and rich built-in methods
- Used in data processing, student records, and product lists
Lists are an essential part of Python programming and are widely used in both beginner and advanced applications.
Creating a List in Python
Lists are created using square brackets [].
numbers = [1, 2, 3, 4, 5]
names = ["Alice", "Bob", "Charlie"]
mixed = [1, "Python", 3.5, True]
Types of Lists in Python
Simple List
marks = [80, 85, 90, 95]
Mixed List
data = [101, "Python", 9.8, False]
Nested List
matrix = [[1, 2, 3], [4, 5, 6]]
Empty List
empty_list = []
Accessing and Slicing List Elements
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # [20, 30, 40]
Modifying and Managing Lists
fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango"
fruits.append("orange")
fruits.insert(1, "grapes")
fruits.extend(["kiwi", "pear"])
fruits.remove("apple")
fruits.pop()
fruits.pop(1)
del fruits[0]
Looping and List Comprehension
for fruit in fruits:
print(fruit)
squares = [x*x for x in range(1, 6)]
print(squares)