githubEdit

Lists

Lists are ordered, mutable collections. They can hold mixed types and be resized as needed.

Creating Lists

numbers = [1, 2, 3]
mixed = ["Apple", 12, 45.7, False]
nested = ["Apple", ["Banana", "Cherry"], "Durian"]

Accessing Items

fruits = ["Apple", "Banana", "Cherry"]

print(fruits[0])   # Apple
print(fruits[-1])  # Cherry

Slicing

letters = ["P", "y", "t", "h", "o", "n"]
print(letters[2:5])  # ['t', 'h', 'o']
print(letters[:3])   # ['P', 'y', 't']
print(letters[3:])   # ['h', 'o', 'n']

Updating Items

Adding Items

Removing Items

Common Methods

Method
Purpose

append()

add one item to end

extend()

add many items

insert()

insert at index

remove()

remove by value

pop()

remove by index (default last)

clear()

remove all items

index()

find first index

count()

count occurrences

sort()

sort list in place

reverse()

reverse in place

copy()

shallow copy

List Comprehensions

Iteration

Next | Previous

Last updated