List and List Methods
✕1. Lists
- Imagine a shopping list on paper. It holds multiple items in order, and we can add, remove, or change items anytime.
A Python list works in a similar way. A list is a data type in Python used to store multiple items in a single variable.
A list is:
✅ Ordered
✅ Mutable
✅ Written inside square brackets
[ ]✅ Able to store different data types 👉 Ordered means items keep their position unless we change the list. 👉 Mutable means we can change, add, or remove items after the list is created. Example:fruits = ["apple", "banana", "orange"]print(fruits)# ➜ ["apple", "banana", "orange"] - Lists are created by placing items inside square brackets
[ ]and separating them with commas. Examples:int_list = [1, 2, 3]str_list = ["apple", "banana", "orange"]empty_list = []print(int_list)print(str_list)print(empty_list) - A list can store items of any valid Python data type.
Example:
student = ["Ram", 15, 85.5, True]print(student)Output: ["Ram", 15, 85.5, True] Here: "Ram" ➜ String 15 ➜ Integer 85.5 ➜ Float True ➜ Boolean - Imagine a class register where each row has a student's name and age.
Example:
Ram 15
Hari 16
Sita 14
A nested list can store this kind of grouped data. A list inside another list is called a nested list.
Example:
student_info = [["Ram", 15], ["Hari", 16], ["Sita", 14]]print(student_info)Output: [["Ram", 15], ["Hari", 16], ["Sita", 14]] Nested lists are useful when we want to store grouped data.
1.1 What is a List?
1.2 Creating Lists
1.3 List Items Can Have Different Data Types
1.4 Nested Lists
2. 🔎 Accessing List Items
- Indexing is used to access a single item from a list. Each item in a list can be accessed using positive or negative index.
Example:
marks = [10, 20, 30, 40, 50]Index positions: 10 20 30 40 50 0 1 2 3 4 -5 -4 -3 -2 -1print(marks[0])# ➜ 10print(marks[-5])# ➜ 10print(marks[4])# ➜ 50print(marks[-1])# ➜ 50 my_list = [10, 20, 30, 40, 50]first_element = my_list[0]print(first_element)# ➜ 10print(my_list[2])# ➜ 30print(my_list[-1])# ➜ 50- Lists are mutable. This means we can change list items after the list is created.
Example:
my_list = [10, 20, 30, 40, 50]my_list[1] = 25print(my_list)# ➜ [10, 25, 30, 40, 50] Here, the value at index 1 changed from 20 to 25. - To access items from a nested list, we use multiple indexes.
Example:
two_d_list = [[1, 2], ["cat", "dog"], [5, 6]]print(two_d_list[0])# ➜ [1, 2]print(two_d_list[0][1])# ➜ 2print(two_d_list[1][0])# ➜ cat Here:two_d_list[0]accesses the first inner list.two_d_list[0][1]accesses the second item of the first inner list. - Slicing is used to extract a part of a list.
Syntax:
list_name[start:stop:step]start ➜ Starting index stop ➜ Stopping index, but not included step ➜ Number of items to skip 📌 Start is included. 📌 Stop is not included. 📌 Step is optional. 📌 If start is not given, slicing begins from the start. 📌 If stop is not given, slicing continues till the end. my_list = [10, 20, 30, 40, 50]print(my_list[1:4])# ➜ [20, 30, 40]print(my_list[0:5:2])# ➜ [10, 30, 50]print(my_list[:3])# ➜ [10, 20, 30]print(my_list[2:])# ➜ [30, 40, 50]print(my_list[::-1])# ➜ [50, 40, 30, 20, 10]index()finds the position of the first occurrence of a value in a list. Example:my_list = [10, 20, 30, 40, 20, 50]index_of_30 = my_list.index(30)print(index_of_30)# ➜ 2print(my_list.index(20))# ➜ 1print(my_list.index(60))# ➜ ValueError ⚠️ This line gives an error because 60 is not found in the list. 📌 ValueError means Python could not complete the action because the value was not found in the list. 📌 Lists do not havefind()like strings. 📌 Useindex()when you are sure the value exists.
2.1 Indexing [ ]
2.2 Indexing Examples
2.3 Lists are Mutable
2.4 Accessing Items from Nested Lists
2.5 Slicing [start:stop:step]
2.6 Slicing Examples
2.7 Finding Index using index()
3. 🔁 Basic List Operations
- Repetition is used to repeat list items multiple times.
Example:
my_list = [1, 2, 3]repeated_list = my_list * 3print(repeated_list)# ➜ [1, 2, 3, 1, 2, 3, 1, 2, 3]print([0] * 5)# ➜ [0, 0, 0, 0, 0]print(["a", "b"] * 4)# ➜ ["a", "b", "a", "b", "a", "b", "a", "b"] - Concatenation means combining two or more lists. The
+operator is used for list concatenation. Example:list_1 = [1, 2, 3]list_2 = [4, 5, 6]list_3 = list_1 + list_2print(list_3)# ➜ [1, 2, 3, 4, 5, 6] 📌 Concatenation creates a new list.
3.1 Repetition (*)
3.2 Concatenation (+)
4. ➕➖ Adding and Removing List Items
append()adds one item to the end of a list. It modifies the original list. Example:my_list = [1, 2, 3]my_list.append(4)print(my_list)# ➜ [1, 2, 3, 4]my_list.append([5, 6])print(my_list)# ➜ [1, 2, 3, 4, [5, 6]] 📌append()adds the given item as a single item.extend()adds all items from another iterable to the end of the list. It modifies the original list. Example:list_1 = [1, 2, 3]list_2 = [4, 5, 6]list_1.extend(list_2)print(list_1)# ➜ [1, 2, 3, 4, 5, 6] 📌append()adds one item. 📌extend()adds multiple items from another list.list_1 = [1, 2, 3]list_1.append([4, 5])print(list_1)# ➜ [1, 2, 3, [4, 5]]list_2 = [1, 2, 3]list_2.extend([4, 5])print(list_2)# ➜ [1, 2, 3, 4, 5]insert()adds an item at a specific index. Other items are shifted to the right. Example:my_list = [1, 2, 4]my_list.insert(2, 3)print(my_list)# ➜ [1, 2, 3, 4]my_list.insert(0, 0)print(my_list)# ➜ [0, 1, 2, 3, 4]my_list.insert(10, 5)print(my_list)# ➜ [0, 1, 2, 3, 4, 5] 📌 If the index is greater than list length, the item is added at the end.pop()removes and returns an item from a list. By default, it removes the last item. Example:my_list = [10, 20, 30, 40, 50]last_element = my_list.pop()print(last_element)# ➜ 50print(my_list)# ➜ [10, 20, 30, 40]second_element = my_list.pop(1)print(second_element)# ➜ 20print(my_list)# ➜ [10, 30, 40] 📌 pop() is useful when we need both the removed item and the updated list.remove()removes the first occurrence of a specified value from a list. Example:my_list = [1, 2, 3, 4, 2]my_list.remove(2)print(my_list)# ➜ [1, 3, 4, 2]my_list.remove(5)# ➜ ValueError ⚠️ This line gives an error because 5 is not found in the list. 📌 ValueError means Python could not complete the action because the value was not found in the list. 📌remove()removes by value. 📌pop()removes by index.
4.1 append()
4.2 extend()
4.3 append() vs extend()
4.4 insert()
4.5 pop()
4.6 remove()
5. 🔃 Sorting, Copying, and Common Functions
sort()sorts the original list in-place. 📌 In-place means the original list itself is changed, rather than creating a new list. Example:my_list = [3, 1, 4, 2]my_list.sort()print(my_list)# ➜ [1, 2, 3, 4] 📌sort()changes the original list.sorted()returns a new sorted list and does not change the original list. Example:my_list = [3, 1, 4, 2]sorted_list = sorted(my_list)print(sorted_list)# ➜ [1, 2, 3, 4]print(my_list)# ➜ [3, 1, 4, 2] 📌sorted()creates a new list.str_list = ["apple", "ball", "cat"]str_list.sort(reverse=True)print(str_list)# ➜ ["cat", "ball", "apple"]- We can sort strings by their length using
key=len. Example:str_list = ["apple", "ball", "cat"]str_list.sort(key=len)print(str_list)# ➜ ["cat", "ball", "apple"] 📌 "cat" has 3 letters, "ball" has 4 letters, and "apple" has 5 letters. copy()creates a copy of a list. This is useful when we want to modify the copied list without changing the original list. Example:original_list = [1, 2, 3]copied_list = original_list.copy()copied_list.append(4)print(original_list)# ➜ [1, 2, 3]print(copied_list)# ➜ [1, 2, 3, 4]- Some functions are useful for numeric lists, while others work with any list.
Common Functions:
sum()➜ Adds all numbersmin()➜ Finds smallest valuemax()➜ Finds largest valuelen()➜ Counts number of itemscount()➜ Counts occurrence of a value Examples:num_list = [1, 2, 3, 4, 5]print(sum(num_list))# ➜ 15print(min(num_list))# ➜ 1print(max(num_list))# ➜ 5print(len(num_list))# ➜ 5print(num_list.count(2))# ➜ 1print(num_list.count(10))# ➜ 0str_list = ["apple", "banana", "apple"]print(str_list.count("apple"))# ➜ 2print(str_list.count("orange"))# ➜ 0
5.1 sort()
5.2 sorted()
5.3 Sorting in Descending Order
5.4 Sorting by Length
5.5 Copying Lists
5.6 Numeric and Common Functions
Practice QuestionsNot started
1. Creating and Accessing Lists
Question 1 of 5
- Create a list named
student_nameswith names of five students. - Create a list named
markswith marks in five subjects. - Display the first student name.
- Display the last student name using negative indexing.
- Display the second and third marks using slicing.
- Change the second student name to "Python" and display the updated list.
- Create a nested list in this format:
[[name_1, age_1], [name_2, age_2], [name_3, age_3]]. Display the second student's age.
Practice creating and accessing list items:- Create a list named
2. Marks and Subjects
Question 2 of 5
- Display total marks.
- Display average marks.
- Display highest marks.
- Display lowest marks.
- Display marks obtained in English in this format:
Mark obtained in English is 89 - Display marks obtained in the second last subject.
- Display marks in the last two subjects.
- Display marks in the first three subjects.
- Display the name of the subject in which the student scored highest marks.
- Display the name of the subject in which the student scored lowest marks.
- Display the number of subjects in which the student scored 80.
Createsubject_list = ["Math", "Science", "English", "Computer", "Nepali"]andmark_list = [80, 75, 89, 95, 80]3. Modifying Lists
Question 3 of 5
- Find the position of the first occurrence of "harry_potter".
- Remove the first occurrence of "harry_potter" and display the list.
- Ask user for a book name and check if it is present in the list.
- Add "the_hobbit" to the end of the list and display it.
- Insert "game_of_thrones" at index 2 and display the list.
- Count and display how many times "lord_of_rings" is present in the list.
- Remove the book from the second position.
- Display the removed book.
- Display the updated book list.
- Display the total number of books in the list.
- Display all books separated by comma.
Createbook_list = ["harry_potter", "lord_of_rings", "harry_potter", "math", "science"]4. Combining, Sorting, and Copying Lists
Question 4 of 5
- Create
list_1 = [1, 2, 3]andlist_2 = [4, 5, 6]. - Combine both lists using
+and display the result. - Extend
list_1usinglist_2and displaylist_1. - Create
book_list = ["harry_potter", "lord_of_rings", "math"]. - Create
book_2 = ["math", "science", "history"]. - Add all books from
book_2tobook_listand display the result. - Sort
book_listin ascending order and display it. - Sort
book_listin descending order and display it. - Sort
book_listbased on length of book name and display it. - Create a copy of
book_list. - Add a new book to the copied list.
- Display both original and copied lists.
Practice combining, sorting, and copying lists:- Create
5. List Practice Challenge
Question 5 of 5
- Display the first item.
- Display the last item.
- Add "tea" to the list.
- Insert "milk" at index 1.
- Remove "salt" from the list.
- Remove the last item using
pop(). - Display the removed item.
- Display the updated shopping list.
- Display the total number of items.
- Display all shopping items separated by comma.
Create a shopping listshopping_list = ["rice", "oil", "salt", "sugar"]
