Tuesday, August 26, 2025

๐ŸLISTS IN PYTHON

Lists are one of the most commonly used data structures in Python. They allow you to store ordered collections of items that can be modified.

1) What is a List?

A list is an ordered collection of items, enclosed in square brackets [ ]. Lists can contain items of different types: integers, strings, floats, or even other lists.


# Example of a list
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = ["Alice", 25, True, 3.14]
nested = [[1, 2], [3, 4]]

2) Accessing Elements

Use indexing to access list elements. Python uses 0-based indexing.


fruits = ["apple", "banana", "cherry"]
print(fruits[0])    # apple
print(fruits[2])    # cherry
print(fruits[-1])   # cherry (last element)

Note: Using an index out of range gives IndexError.

3) Adding Elements

You can add items to a list using append(), insert(), or extend().


fruits = ["apple", "banana"]

fruits.append("cherry")         # Add at the end
fruits.insert(1, "orange")      # Add at specific index
fruits.extend(["mango", "kiwi"]) # Add multiple items

print(fruits)
# Output: ['apple', 'orange', 'banana', 'cherry', 'mango', 'kiwi']

4) Removing Elements

You can remove elements using remove(), pop(), or del.


fruits = ["apple", "banana", "cherry"]

fruits.remove("banana")   # Remove by value
popped = fruits.pop()     # Remove last element
del fruits[0]             # Remove by index

print(fruits)
# Output: []

Common Mistakes:

  • Using remove() on an element that doesn’t exist → ValueError
  • Accessing or deleting index out of range → IndexError

5) Slicing and Iterating

Lists can be sliced to access a range of elements and iterated with loops.


fruits = ["apple", "banana", "cherry", "mango"]

# Slicing
print(fruits[1:3])   # ['banana', 'cherry']
print(fruits[:2])    # ['apple', 'banana']
print(fruits[::2])   # ['apple', 'cherry']

# Iterating
for fruit in fruits:
    print(fruit)

6) Common List Methods

  • append() – Add item to end
  • insert() – Add item at index
  • extend() – Add multiple items
  • remove() – Remove item by value
  • pop() – Remove item by index or last element
  • sort() – Sort list in ascending order
  • reverse() – Reverse the list
  • index() – Find index of item
  • count() – Count occurrences of item

7) Common Mistakes

  • Using parentheses instead of brackets → fruits("apple") ❌
  • Trying to access index out of range → fruits[10] ❌
  • Confusing append() and extend()
  • Modifying a list while iterating over it → unexpected behavior

๐Ÿ–ฅ️ Practice in Browser

No comments:

Post a Comment

๐ŸWhat is scikitlearn??