Day 8: Mastering Python Lists
Lists are one of the most powerful and frequently used data structures in Python. Whether you're working in Data Science, Web Development, or DSA, lists are everywhere.
In this session, we focus on understanding lists through practical usage, so you build strong logic instead of just memorizing syntax.
What is a List?
A list is a collection of multiple items stored in a single variable.
numbers = [10, 20, 30, 40, 50]
Key Properties:
- Ordered (index-based)
- Mutable (can be changed)
- Allows duplicate values
- Can store mixed data types
Basic Operations on Lists
1. Creating a List
nums = [1, 2, 3, 4, 5]
2. Accessing Elements
print(nums[0]) # First element
print(nums[-1]) # Last element
3. Adding Elements
nums.append(6) # Add at end
nums.insert(1, 100) # Insert at specific position
4. Removing Elements
nums.remove(3) # Remove specific value
nums.pop() # Remove last element
Intermediate Concepts
1. Sum of Elements
nums = [1, 2, 3, 4]
print(sum(nums))
2. Finding Maximum
print(max(nums))
3. Reversing a List
nums.reverse()
OR
nums = nums[::-1]
4. Counting Frequency
nums = [1, 2, 2, 3, 2]
print(nums.count(2))
Advanced List Handling
1. Removing Duplicates
nums = [1, 2, 2, 3, 4, 4]
unique = list(set(nums))
2. Merging Two Lists Without Duplicates
a = [1, 2, 3]
b = [3, 4, 5]
merged = list(set(a + b))
3. Second Largest Element
nums = [10, 20, 4, 45, 99]
nums = list(set(nums))
nums.sort()
print(nums[-2])
4. Flattening a Nested List
nested = [[1, 2], [3, 4], [5]]
flat = [item for sublist in nested for item in sublist]
Important Notes
- Lists are dynamic, meaning they can grow or shrink
- Use built-in functions for efficiency instead of manual loops
- Avoid unnecessary nested loops when list comprehension can solve it
- Always think in terms of time complexity (important for DSA)
Practice Questions
Basic
- Create a list of 5 numbers and print it
- Access first and last element
- Add an element to a list
- Remove an element from a list
Intermediate
- Find the sum of all elements in a list
- Find the largest element
- Reverse a list
- Count frequency of an element
Advanced
- Remove duplicates from a list
- Merge two lists without duplicates
- Find second largest number
- Flatten a nested list
.png)

0 Comments:
Post a Comment