Lists and List Methods

What are Lists?

Lists are ordered, mutable collections that can hold items of any type.

Creating Lists

numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]
empty = []

Accessing Elements

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

Slicing

numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4])    # [1, 2, 3]
print(numbers[:3])     # [0, 1, 2]
print(numbers[3:])     # [3, 4, 5]
print(numbers[::2])    # [0, 2, 4] (every 2nd item)

Common List Methods

append() - Add item to end

fruits = ["apple", "banana"]
fruits.append("cherry")
# ["apple", "banana", "cherry"]

insert() - Add item at position

fruits.insert(1, "orange")
# ["apple", "orange", "banana", "cherry"]

remove() - Remove first occurrence

fruits.remove("banana")

pop() - Remove and return item

last = fruits.pop()     # Removes last item
first = fruits.pop(0)   # Removes first item

sort() - Sort list in place

numbers = [3, 1, 4, 1, 5]
numbers.sort()  # [1, 1, 3, 4, 5]

reverse() - Reverse list

numbers.reverse()

count() - Count occurrences

numbers.count(1)  # Returns 2

index() - Find position

fruits.index("cherry")  # Returns index of "cherry"

List Comprehensions

Create lists in a concise way

squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Checking Membership

if "apple" in fruits:
    print("Found apple!")

List Length

len(fruits)  # Returns number of items

Lists and List Methods

points

You earned points! 🎉 Keep practicing! 💪

Sign up to save your points and access 10,000+ exercises Sign up to track your progress and access 10,000+ exercises

Daily Limit Reached

🔥 exercises left — Upgrade for more!

This module requires

Try the first module of this course for free, then upgrade to unlock all modules and exercises.

No exercise selected

Click "New Exercise" to begin

Generating exercise...

Syntax Syntax OK Syntax off

Write a short answer to the question above (2-5 sentences).

Score
+ /
Base /10
Bonus
×
Total
+

Feedback

Tip

Your Solution

Correct Solution