Lists in Python
Lists in Python
1. Introduction to Lists
• A list is a built-in data structure in Python that can store multiple
values of different types.
• Lists are mutable, meaning they can be modified after creation.
• They are enclosed within square brackets [ ] and elements are
separated by commas ,.
Examples:
# Empty list
list1 = []
# List of integers
list2 = [1, 2, 3, 4, 5]
# List of strings
list4 = ["apple", "banana", "cherry"]
2. Creating Lists
3. Accessing Elements
4. Modifying Lists
Changing an Element
list1[1] = "C#"
print(list1) # Output: ['Python', 'C#', 'C++', 'JavaScript']
Appending Elements (.append())
list1.append("Ruby")
print(list1) # Output: ['Python', 'C#', 'C++', 'JavaScript', 'Ruby']
list1.insert(2, "Swift")
print(list1) # Output: ['Python', 'C#', 'Swift', 'C++', 'JavaScript', 'Ruby']
5. List Operations
Concatenation (+)
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list1 + list2
print(result) # Output: [1, 2, 3, 4, 5, 6]
Replication (*)
list1 = [0, 1]
print(list1 * 3) # Output: [0, 1, 0, 1, 0, 1]
6. List Slicing
7. List Methods
8. Two-Dimensional Lists (2D Lists)
Creating a 2D List
Accessing Elements
Modifying Elements
matrix[1][1] = 10
print(matrix) # Output: [[1, 2, 3], [4, 10, 6], [7, 8, 9]]
9. Iterating Over Lists
*Note
Lists are ordered, mutable, and can store multiple data types.
Operations include concatenation (+), replication (*), slicing, and looping.
List methods like append(), pop(), remove(), and sort() help manage elements.
2D Lists store tabular data and are accessed using two indices.
List comprehensions provide a compact way to create lists.
Searching can be done using linear search.
User inputs can be taken in space-separated or multi-line format.