About Lesson
-
Creating, Accessing, and Modifying Lists
- Definition: A list is an ordered collection of items that can be of different data types. Lists are mutable, meaning their elements can be changed.
- Creating Lists: python
my_list = [1, 2, 3, 4, 5]
- Accessing Elements: Use indexing to access elements. Indexing starts at 0. python
print(my_list[0]) # Output: 1
- Modifying Elements: Assign a new value to a specific index. python
my_list[0] = 10 print(my_list) # Output: [10, 2, 3, 4, 5]
- Adding Elements: Use
append()
to add an element at the end, orinsert()
to add an element at a specific position. pythonmy_list.append(6) my_list.insert(1, 15) print(my_list) # Output: [10, 15, 2, 3, 4, 5, 6]
- Removing Elements: Use
remove()
to remove a specific element, orpop()
to remove an element at a specific index. pythonmy_list.remove(15) my_list.pop(0) print(my_list) # Output: [2, 3, 4, 5, 6]
List Comprehensions
- Definition: A concise way to create lists using a single line of code. It can include conditions and loops.
- Syntax: python
new_list = [expression for item in iterable if condition]
- Example: python
squares = [x**2 for x in range(10)] print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]