Codeskill

Learn to code, step by step

Lists and Tuples: Organizing Data in Python

Lists and tuples in Python. Two ways to store collections of items, when to use each, and how to work with them.

Understanding lists in Python

A list is an ordered collection of items. It is mutable – you can add, remove, and change elements after creation. Lists can hold mixed data types.

Creating a list

Put comma-separated values inside square brackets:

fruits = ["apple", "banana", "cherry"]
print(fruits)

Accessing elements

Lists are ordered, so each item has an index. Indexing starts at 0:

print(fruits[1])  # Outputs: banana

Modifying lists

Because lists are mutable, you can change them in place:

fruits.append("orange")  # Adds 'orange' at the end
fruits[0] = "kiwi"       # Changes 'apple' to 'kiwi'
del fruits[2]            # Removes 'cherry'

Iterating through a list

A for loop runs code for each item:

for fruit in fruits:
    print(fruit)

List comprehensions

A compact way to build a new list from an existing sequence:

squares = [x**2 for x in range(10)]
print(squares)  # Outputs squares of numbers from 0 to 9

Understanding tuples in Python

Tuples store collections like lists, but they are immutable – once created, you cannot change the contents. Defined with parentheses ().

Creating a tuple

Comma-separated values inside parentheses:

dimensions = (200, 50)
print(dimensions)

Accessing tuple elements

Same indexing as lists:

print(dimensions[0])  # Outputs: 200

You cannot modify a tuple after creation. That immutability is the point – use tuples when the data should not change.

When to use lists and tuples

Simple rule of thumb:

  • Lists when the collection might change – user names, scores, anything you will add to or remove from.
  • Tuples when the data is fixed – coordinates, days of the week, anything that should stay put. Tuples are slightly faster and prevent accidental changes.

Best practices

  • Pick list or tuple based on whether the data needs to change.
  • Keep collections reasonably short – very long sequences get hard to read.
  • Use list comprehensions when you need a new list derived from an existing one.

Lists and tuples turn up constantly in Python. Knowing which to reach for – mutable or fixed – saves bugs and keeps code clearer.

PreviousFunctions in Python: Reusing Code Effectively