DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Python Lists Explained: Create, Access, and Modify Elements

Lists are one of the most useful data structures in Python. They store an ordered collection of items that can be of different types.

What is a list?

A list is a collection of items enclosed in square brackets []. Items are separated by commas.

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [10, "hello", True, 3.14]
Enter fullscreen mode Exit fullscreen mode

Lists maintain order, so the first item added stays first.

You can also create an empty list:

empty_list = []
Enter fullscreen mode Exit fullscreen mode

Accessing elements with indexes

Each item in a list has a position called an index. Indexes start at 0.

fruits = ["apple", "banana", "cherry"]

print(fruits[0])  # apple
print(fruits[1])  # banana
print(fruits[2])  # cherry
Enter fullscreen mode Exit fullscreen mode

Use negative indexes to access from the end:

print(fruits[-1])  # cherry (last item)
print(fruits[-2])  # banana
Enter fullscreen mode Exit fullscreen mode

Modifying lists

Lists are mutable, which means you can change items after creation.

Change an item by index:

fruits[1] = "orange"
print(fruits)  # ["apple", "orange", "cherry"]
Enter fullscreen mode Exit fullscreen mode

Add items with append():

fruits.append("grape")
print(fruits)  # ["apple", "orange", "cherry", "grape"]
Enter fullscreen mode Exit fullscreen mode

Getting the length

Use len() to find how many items a list has:

print(len(fruits))  # 4
Enter fullscreen mode Exit fullscreen mode

Common examples

Work with a list of scores:

scores = [85, 92, 78, 90]

print(scores[0])     # First score: 85
print(scores[-1])    # Last score: 90
scores.append(88)
print(len(scores))   # 5
Enter fullscreen mode Exit fullscreen mode

Common mistake: IndexError

Trying to access an index that does not exist causes an error.

fruits = ["apple", "banana"]

print(fruits[5])  # IndexError: list index out of range
Enter fullscreen mode Exit fullscreen mode

Always check the length with len() if needed, or use valid indexes.

Quick summary

  • Create lists with square brackets [].
  • Access items with indexes starting at 0.
  • Use negative indexes for the end of the list.
  • Modify items directly or use append() to add new ones.
  • Use len() to get the number of items.

Practice creating and modifying lists. They are essential for storing and working with collections of data in Python programs.

Top comments (0)