easycodelearning.com
🐍 Learn Python Online
Back to All Tutorials

Lists & Collections

What is a List?

A list is a collection of items stored in a single variable. Lists are ordered, mutable (changeable), and allow duplicate values.

Creating Lists

# Empty list
empty_list = []

# List of numbers
numbers = [1, 2, 3, 4, 5]

# List of strings
fruits = ["apple", "banana", "orange"]

# Mixed list
mixed = [1, "hello", 3.14, True]

Accessing List Items

Access items using their index (starting from 0):

fruits = ["apple", "banana", "orange"]
print(fruits[0])   # Output: apple
print(fruits[1])   # Output: banana
print(fruits[-1])  # Output: orange (last item)

List Length

Use len() to get the number of items:

fruits = ["apple", "banana", "orange"]
print(len(fruits))  # Output: 3

Adding Items

append() - Add to end

fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits)  # Output: ['apple', 'banana', 'orange']

insert() - Add at specific position

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

Removing Items

remove() - Remove specific item

fruits = ["apple", "banana", "orange"]
fruits.remove("banana")
print(fruits)  # Output: ['apple', 'orange']

pop() - Remove by index

fruits = ["apple", "banana", "orange"]
fruits.pop(1)  # Removes "banana"
print(fruits)  # Output: ['apple', 'orange']

List Methods

sort() - Sort items

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

reverse() - Reverse order

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

count() - Count occurrences

numbers = [1, 2, 2, 3, 2, 4]
print(numbers.count(2))  # Output: 3

Looping Through Lists

fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)
# Output:
# apple
# banana
# orange

List Slicing

Get a portion of a list:

numbers = [1, 2, 3, 4, 5]
print(numbers[1:4])   # Output: [2, 3, 4]
print(numbers[:3])    # Output: [1, 2, 3]
print(numbers[2:])    # Output: [3, 4, 5]

Key Takeaways

  • Lists store multiple items in one variable
  • Access items using index (starting from 0)
  • Use append() to add items
  • Use remove() or pop() to remove items
  • Use sort() and reverse() to organize items
  • Loop through lists with for loops

Practice Time

Create a list of your favorite items, add and remove items, and practice sorting and looping!

Open Code Editor
Next: Conditional Statements