Kahibaro
Discord Login Register

Lists

Understanding Lists in Python

Lists are one of the most commonly used data collections in Python. They are ordered, changeable (mutable), and can hold a mix of different data types.

This chapter focuses specifically on how to create, use, and modify lists.

Creating Lists

A list is written with square brackets [], with items separated by commas.

numbers = [1, 2, 3, 4]
names = ["Alice", "Bob", "Charlie"]
mixed = [1, "hello", 3.14, True]
empty_list = []

You can also create a list using the list() function:

text = "hello"
characters = list(text)  # ['h', 'e', 'l', 'l', 'o']

Accessing List Items (Indexing)

List items are ordered. Each item has a position (index), starting from 0.

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

Negative indexes count from the end:

print(fruits[-1])  # cherry
print(fruits[-2])  # banana

Changing Items in a List

Lists are mutable, so you can change items after the list is created.

fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits)  # ['apple', 'blueberry', 'cherry']

You can also change several items at once using slicing (explained next).

Slicing Lists

Slicing lets you get a part (sub-list) of a list.

General form:

$$
\text{list}[start:end]
$$

numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])  # [20, 30, 40]
print(numbers[:3])   # [10, 20, 30]   (from start to index 2)
print(numbers[2:])   # [30, 40, 50]   (from index 2 to end)

You can also use slices to replace multiple items:

numbers = [0, 1, 2, 3, 4, 5]
numbers[1:4] = [10, 11, 12]
print(numbers)  # [0, 10, 11, 12, 4, 5]

Adding Items to a List

`append()` – add to the end

append() adds a single item to the end of the list.

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

`insert()` – add at a specific position

insert(index, item) inserts an item at a specific position, moving later items to the right.

fruits = ["apple", "cherry"]
fruits.insert(1, "banana")
print(fruits)  # ['apple', 'banana', 'cherry']

`extend()` – add multiple items

extend() adds all items from another list (or any iterable) to the end.

fruits = ["apple", "banana"]
more_fruits = ["cherry", "date"]
fruits.extend(more_fruits)
print(fruits)  # ['apple', 'banana', 'cherry', 'date']

Removing Items from a List

`remove()` – remove by value

Removes the first matching value.

fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana")
print(fruits)  # ['apple', 'cherry', 'banana']

If the value is not in the list, remove() causes an error.

`pop()` – remove by index

Removes and returns the item at a given index. If no index is given, removes the last item.

fruits = ["apple", "banana", "cherry"]
last = fruits.pop()
print(last)    # cherry
print(fruits)  # ['apple', 'banana']
first = fruits.pop(0)
print(first)   # apple
print(fruits)  # ['banana']

`del` – delete by index or slice

del is a Python keyword used to delete items.

numbers = [10, 20, 30, 40, 50]
del numbers[1]      # delete item at index 1
print(numbers)      # [10, 30, 40, 50]
del numbers[1:3]    # delete a slice
print(numbers)      # [10, 50]

`clear()` – remove all items

Empties the list but keeps the list object.

numbers = [1, 2, 3]
numbers.clear()
print(numbers)  # []

Checking if an Item Is in a List

Use the in keyword to test if a value exists in the list.

fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)   # True
print("orange" in fruits)   # False
if "apple" in fruits:
    print("We have apples!")

Getting the Length of a List

Use len() to find out how many items are in a list.

fruits = ["apple", "banana", "cherry"]
count = len(fruits)
print(count)  # 3

Looping Over a List

You will learn loops in detail elsewhere, but here is how they commonly work with lists.

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

This prints each item in the list, one per line.

Sorting and Reversing Lists

`sort()` – sort the list in place

sort() changes the existing list into a sorted version.

numbers = [3, 1, 4, 1, 5]
numbers.sort()
print(numbers)  # [1, 1, 3, 4, 5]
fruits = ["banana", "apple", "cherry"]
fruits.sort()
print(fruits)   # ['apple', 'banana', 'cherry']

You can sort in reverse order:

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

`sorted()` – return a new sorted list

sorted() does not change the original list; it returns a new one.

numbers = [3, 1, 4, 1, 5]
sorted_numbers = sorted(numbers)
print(numbers)         # [3, 1, 4, 1, 5]
print(sorted_numbers)  # [1, 1, 3, 4, 5]

`reverse()` – reverse the list order

Reverses the list in place, without sorting.

numbers = [1, 2, 3, 4]
numbers.reverse()
print(numbers)  # [4, 3, 2, 1]

Copying Lists

Assigning one list to another variable does not make a copy; it makes a second name for the same list.

a = [1, 2, 3]
b = a       # NOT a copy!
b.append(4)
print(a)    # [1, 2, 3, 4]
print(b)    # [1, 2, 3, 4]

To make a real (shallow) copy, use one of these:

a = [1, 2, 3]
b = a.copy()
# or
b = list(a)
# or
b = a[:]   # slice from start to end
b.append(4)
print(a)  # [1, 2, 3]
print(b)  # [1, 2, 3, 4]

Joining and Repeating Lists

Joining lists with `+`

a = [1, 2]
b = [3, 4]
c = a + b
print(c)  # [1, 2, 3, 4]

Repeating lists with `*`

zeros = [0] * 5
print(zeros)  # [0, 0, 0, 0, 0]

Useful List Methods (Overview)

Some common list methods you have seen or will see:

Example of index() and count():

numbers = [1, 2, 3, 2, 2, 4]
print(numbers.index(3))  # 2 (position of first 3)
print(numbers.count(2))  # 3 (three 2's)

Simple Practice Ideas with Lists

Some small ideas to practice working with lists:

Lists are a core part of Python programming, and you will use them again in loops, functions, file handling, and many later topics.

Views: 11

Comments

Please login to add a comment.

Don't have an account? Register now!