Python_List
Python_List
Definition of a List:
A list in Python is an ordered, mutable collection of elements that
allows duplicate values. Lists are
one of the most commonly used data structures in Python and can
hold elements of different data types.
Characteristics of a List:
- Ordered: The order of elements is maintained.
- Mutable: Elements can be modified, added, or removed.
- Allows Duplicates: A list can contain repeated elements.
- Heterogeneous: A list can contain different data types.
- Indexing & Slicing Supported: Elements can be accessed via their
index.
- Dynamic Size: Lists can grow or shrink as needed.
Creating a List:
1. Using Square Brackets []
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [10, "hello", 3.14, True]
Modifying a List:
1. Changing an Element
fruits[1] = "mango"
2. Adding Elements:
fruits.append("orange") # Adds to the end
fruits.insert(1, "grape") # Adds at a specific index
3. Removing Elements:
fruits.remove("apple") # Removes first occurrence
fruits.pop() # Removes the last element
List Operations:
1. Concatenation (+)
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
2. Repetition (*)
numbers = [1, 2, 3] * 3
Sorting a List:
1. Using sort()
numbers.sort()
2. Using sorted()
sorted_numbers = sorted(numbers)
Reversing a List:
numbers.reverse()
Copying a List:
1. Using copy()
list_copy = numbers.copy()
Nested Lists:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[1][2]) # Output: 6
Applications of Lists:
1. Storing a collection of items
2. Handling dynamic data
3. Representing matrices or graphs
4. Efficient searching and sorting
5. Processing data using loops
Summary:
- Ordered collection
- Mutable (changeable)
- Allows duplicates
- Supports slicing, sorting, etc.
- Stores different data types
- Supports list comprehension for efficiency