Python Programming Lecture: Lists
Previous Video Recap
- Explored control statements:
- Simple if
- Nested if
- If-else
- Elif
- Completed a coding exercise on creating a log calculator
New Concept: Python Lists
What is a List?
- A list is a data structure used to store multiple items in a single variable.
- Allows for organizing data effectively.
- Comes under sequence data types as it contains a sequence of data.
- Lists can store elements of different data types (integers, strings, booleans, floats, objects) in the same list.
- Homogeneous and heterogeneous collections are allowed.
Creating Lists
# Example of creating lists
roll_numbers = [1, 2, 3, 4, 5]
names = ['John', 'Jane', 'Doe']
mixed_list = [1, 'Hello', True, 10.5]
Characteristics of Lists
- Ordered: Items have a defined order that will not change.
- Mutable: Can be altered after creation (add, remove, change elements).
- Allow Duplicates: Lists can have multiple occurrences of the same element.
Common List Operations
Accessing Elements
- Use index to access individual elements.
roll_numbers[0] # Access first element
roll_numbers[-1] # Access last element (using negative indexing)
Slicing
- Extract subparts of list using slicing.
numbers = [10, 0, -1, 7]
numbers[1:3] # Slicing from index 1 to 2
numbers[:3] # Slicing from start to index 2
numbers[1:] # Slicing from index 1 to end
numbers[::2] # Slicing with step
List Functions and Methods
Adding Elements
- Append: Adds a single element at the end.
numbers.append(45)
- Insert: Adds an element at a specified index.
numbers.insert(2, 45)
- Extend: Adds multiple elements at the end.
numbers.extend([45, 46, 47])
Removing Elements
- Remove: Removes the first occurrence of specific value.
numbers.remove(45)
- Pop: Removes element at a specific index (default is last element) and returns it.
numbers.pop() # Removes last element
numbers.pop(1) # Removes element at index 1
Utility Functions
- Len: Returns length of the list.
len(numbers)
- Min: Returns minimum value.
min(numbers)
- Max: Returns maximum value.
max(numbers)
numbers.sort()
- Reverse: Reverses the list order.
numbers.reverse()
- Index: Finds index of the first occurrence of a value.
numbers.index(7)
- Count: Counts occurrences of a value.
numbers.count(7)
Practical Example
numbers = [10, 0, -1, 7]
# Adding elements
numbers.append(45)
numbers.insert(2, 32)
numbers.extend([50, 60])
# Removing elements
numbers.remove(0)
numbers.pop()
# Utility operations
length = len(numbers) # 10
minimum = min(numbers) # -1
maximum = max(numbers) # 60
numbers.sort()
numbers.reverse()
Final Remarks
- Lists are a powerful and flexible data structure in Python, offering a variety of operation methods.
- Next video will cover the Random Module and a new coding exercise.