Student Grade Prediction

Student Grade Prediction
πŸ“ Finding and removing element in a list

Python lists come with powerful built-in methods that make it easy to work with elements. Two important ones are:

  • .index() β†’ Find the position of an element in a list
  • .pop() β†’ Remove an element from a list and return it

  • .index()

The .index() method is used to locate the position (index) of an element in a list.

πŸ‘‰ Remember: Python lists are zero-indexed (the first element is at position 0).

Example 1:
fruits = ["apple", "banana", "cherry", "orange"]

# Find the position of 'banana'
position = fruits.index('banana')
print(position)   # Output: 1

# Access the element at that position
print(fruits[1]) # Output: banana
Example 2:
# List of student names
students = ["Alice", "Bob", "Charlie", "Diana"]

# Find the index of 'Diana'
print(students.index('Diana'))  # Output: 4

βœ… .index() returns the first matching index of the given element.

  • Note: If the element doesn’t exist, Python raises a ValueError.

  • .pop()

The .pop() method removes an element from a list at a specific index and returns it.

If no index is given, .pop() removes and returns the last element.

Example 1: Removing with .index() + .pop()
fruits = ["apple", "banana", "cherry", "orange"]

position = fruits.index('banana')   # Get index of 'banana'
name = fruits.pop(position)         # Remove and save it

print(name)     # Output: banana
print(fruits)   # Output:  ['apple', 'cherry', 'orange']
Example 2: Removing another element
students = ["Alice", "Bob", "Charlie", "Diana"]

place = students.index('Charlie')   # Find index of 'Charlie'
pos = students.pop(place)           # Remove it

print(pos)     # Output: Charlie
print(students)  # Output: ['Alice', 'Bob', 'Diana']
Summary
  • .index(item) β†’ Finds the index (position) of an item in the list.
  • .pop(index) β†’ Removes the item at the given index and returns it.
  • Together, these methods make it easy to find and remove specific items from a list.

  • Quick Tip: Use .remove(item) if you just want to delete by value without worrying about the index.