Python Lists and Tuples - Detailed Notes
1. Lists in Python
Definition:
A list is a built-in data type in Python used to store multiple values in a single variable. Lists are mutable,
meaning their values can be changed after creation.
Example:
marks = [87, 64, 33, 95, 76]
student = ["Karan", 85, "Delhi"]
You can access elements using indices:
print(student[0]) # Output: Karan
Updating Elements:
student[0] = "Arjun"
print(student) # Output: ['Arjun', 85, 'Delhi']
Finding Length:
len(student) # Output: 3
2. List Slicing
Syntax:
list[start : end]
- start: index to start from (inclusive)
- end: index to end at (exclusive)
Example:
marks = [87, 64, 33, 95, 76]
print(marks[1:4]) # Output: [64, 33, 95]
print(marks[:4]) # Output: [87, 64, 33, 95]
Python Lists and Tuples - Detailed Notes
print(marks[1:]) # Output: [64, 33, 95, 76]
print(marks[-3:-1]) # Output: [33, 95]
3. List Methods
append(el) : Adds el to the end -> list.append(4)
insert(idx, el) : Inserts el at index idx -> list.insert(1, 99)
sort() : Sorts in ascending order -> list.sort()
reverse() : Reverses list -> list.reverse()
sort(reverse=True): Sorts in descending order -> list.sort(reverse=True)
remove(el) : Removes first occurrence of el -> list.remove(1)
pop(idx) : Removes element at index idx -> list.pop(2)
Example:
list1 = [2, 1, 3]
list1.append(4) # [2, 1, 3, 4]
list1.sort() # [1, 2, 3, 4]
list1.reverse() # [4, 3, 2, 1]
list1.remove(3) # [4, 2, 1]
4. Tuples in Python
Definition:
A tuple is like a list, but immutable (cannot be changed after creation).
Example:
tup = (87, 64, 33, 95, 76)
print(tup[0]) # Output: 87
tup[0] = 43 # X Error! Tuples are immutable
Empty and Single Element Tuples:
Python Lists and Tuples - Detailed Notes
tup1 = () # Empty tuple
tup2 = (1,) # Single element tuple
tup3 = (1, 2, 3)
5. Tuple Methods
count(el): Counts how many times el occurs -> tup.count(1)
index(el): Returns the index of first occurrence of el -> tup.index(3)
Example:
tup = (2, 1, 3, 1)
print(tup.count(1)) # Output: 2
print(tup.index(1)) # Output: 1
6. Practice Problems
Q1. WAP to ask the user to enter names of their 3 favorite movies & store them in a list.
movies = []
for i in range(3):
movie = input("Enter your favorite movie: ")
movies.append(movie)
print("Your favorite movies are:", movies)
Q2. WAP to check if a list contains a palindrome of elements.
original = [1, 2, 3, 2, 1]
copy_list = original.copy()
copy_list.reverse()
if original == copy_list:
print("The list is a palindrome.")
else:
print("The list is not a palindrome.")
Python Lists and Tuples - Detailed Notes
Q3. WAP to count the number of students with the "A" grade in the following tuple:
grades = ("C", "D", "A", "A", "B", "B", "A")
print("A grade count:", grades.count("A")) # Output: 3
Q4. Store the above values in a list & sort them from "A" to "D":
grades = ["C", "D", "A", "A", "B", "B", "A"]
grades.sort() # Alphabetical = A -> D
print("Sorted grades:", grades)