List and List Methods

1. Lists

    1.1 What is a List?
    1. 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"]
    1.2 Creating Lists
    1. 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)
    1.3 List Items Can Have Different Data Types
    1. 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
    1.4 Nested Lists
    1. 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.

2. 🔎 Accessing List Items

    2.1 Indexing [ ]
    1. 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 -1 print(marks[0]) # ➜ 10 print(marks[-5]) # ➜ 10 print(marks[4]) # ➜ 50 print(marks[-1]) # ➜ 50
    2.2 Indexing Examples
    1. my_list = [10, 20, 30, 40, 50]first_element = my_list[0] print(first_element) # ➜ 10 print(my_list[2]) # ➜ 30 print(my_list[-1]) # ➜ 50
    2.3 Lists are Mutable
    1. 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] = 25 print(my_list) # ➜ [10, 25, 30, 40, 50] Here, the value at index 1 changed from 20 to 25.
    2.4 Accessing Items from Nested Lists
    1. 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]) # ➜ 2 print(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.
    2.5 Slicing [start:stop:step]
    1. 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.
    2.6 Slicing Examples
    1. 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]
    2.7 Finding Index using index()
    1. 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) # ➜ 2 print(my_list.index(20)) # ➜ 1 print(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 have find() like strings. 📌 Use index() when you are sure the value exists.

3. 🔁 Basic List Operations

    3.1 Repetition (*)
    1. Repetition is used to repeat list items multiple times. Example: my_list = [1, 2, 3]repeated_list = my_list * 3 print(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"]
    3.2 Concatenation (+)
    1. 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_2 print(list_3) # ➜ [1, 2, 3, 4, 5, 6] 📌 Concatenation creates a new list.

4. ➕➖ Adding and Removing List Items

    4.1 append()
    1. 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.
    4.2 extend()
    1. 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.
    4.3 append() vs extend()
    1. 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]
    4.4 insert()
    1. 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.
    4.5 pop()
    1. 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) # ➜ 50 print(my_list) # ➜ [10, 20, 30, 40] second_element = my_list.pop(1) print(second_element) # ➜ 20 print(my_list) # ➜ [10, 30, 40] 📌 pop() is useful when we need both the removed item and the updated list.
    4.6 remove()
    1. 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.

5. 🔃 Sorting, Copying, and Common Functions

    5.1 sort()
    1. 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.
    5.2 sorted()
    1. 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.
    5.3 Sorting in Descending Order
    1. str_list = ["apple", "ball", "cat"]str_list.sort(reverse=True) print(str_list) # ➜ ["cat", "ball", "apple"]
    5.4 Sorting by Length
    1. 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.
    5.5 Copying Lists
    1. 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]
    5.6 Numeric and Common Functions
    1. Some functions are useful for numeric lists, while others work with any list. Common Functions: sum() ➜ Adds all numbers min() ➜ Finds smallest value max() ➜ Finds largest value len() ➜ Counts number of items count() ➜ Counts occurrence of a value Examples: num_list = [1, 2, 3, 4, 5]print(sum(num_list)) # ➜ 15 print(min(num_list)) # ➜ 1 print(max(num_list)) # ➜ 5 print(len(num_list)) # ➜ 5 print(num_list.count(2)) # ➜ 1 print(num_list.count(10)) # ➜ 0 str_list = ["apple", "banana", "apple"]print(str_list.count("apple")) # ➜ 2 print(str_list.count("orange")) # ➜ 0

Practice QuestionsNot started

  1. 1. Creating and Accessing Lists

    Question 1 of 5

      Practice creating and accessing list items:
      1. Create a list named student_names with names of five students.
      2. Create a list named marks with marks in five subjects.
      3. Display the first student name.
      4. Display the last student name using negative indexing.
      5. Display the second and third marks using slicing.
      6. Change the second student name to "Python" and display the updated list.
      7. 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.
  2. 2. Marks and Subjects

    Question 2 of 5

      Create subject_list = ["Math", "Science", "English", "Computer", "Nepali"] and mark_list = [80, 75, 89, 95, 80]
      1. Display total marks.
      2. Display average marks.
      3. Display highest marks.
      4. Display lowest marks.
      5. Display marks obtained in English in this format: Mark obtained in English is 89
      6. Display marks obtained in the second last subject.
      7. Display marks in the last two subjects.
      8. Display marks in the first three subjects.
      9. Display the name of the subject in which the student scored highest marks.
      10. Display the name of the subject in which the student scored lowest marks.
      11. Display the number of subjects in which the student scored 80.
  3. 3. Modifying Lists

    Question 3 of 5

      Create book_list = ["harry_potter", "lord_of_rings", "harry_potter", "math", "science"]
      1. Find the position of the first occurrence of "harry_potter".
      2. Remove the first occurrence of "harry_potter" and display the list.
      3. Ask user for a book name and check if it is present in the list.
      4. Add "the_hobbit" to the end of the list and display it.
      5. Insert "game_of_thrones" at index 2 and display the list.
      6. Count and display how many times "lord_of_rings" is present in the list.
      7. Remove the book from the second position.
      8. Display the removed book.
      9. Display the updated book list.
      10. Display the total number of books in the list.
      11. Display all books separated by comma.
  4. 4. Combining, Sorting, and Copying Lists

    Question 4 of 5

      Practice combining, sorting, and copying lists:
      1. Create list_1 = [1, 2, 3] and list_2 = [4, 5, 6].
      2. Combine both lists using + and display the result.
      3. Extend list_1 using list_2 and display list_1.
      4. Create book_list = ["harry_potter", "lord_of_rings", "math"].
      5. Create book_2 = ["math", "science", "history"].
      6. Add all books from book_2 to book_list and display the result.
      7. Sort book_list in ascending order and display it.
      8. Sort book_list in descending order and display it.
      9. Sort book_list based on length of book name and display it.
      10. Create a copy of book_list.
      11. Add a new book to the copied list.
      12. Display both original and copied lists.
  5. 5. List Practice Challenge

    Question 5 of 5

      Create a shopping list shopping_list = ["rice", "oil", "salt", "sugar"]
      1. Display the first item.
      2. Display the last item.
      3. Add "tea" to the list.
      4. Insert "milk" at index 1.
      5. Remove "salt" from the list.
      6. Remove the last item using pop().
      7. Display the removed item.
      8. Display the updated shopping list.
      9. Display the total number of items.
      10. Display all shopping items separated by comma.