Your First Steps in Python: A Beginner to Intermediate Guide

Lists: Ordered and Mutable Collections

Section 2

Data Structures: Organizing Collections of Data

Your First Steps in Python: A Beginner to Intermediate GuideData Structures: Organizing Collections of Data

Welcome back! In this section, we'll dive into one of Python's most fundamental and versatile data structures: lists. Think of a list as a container where you can store a collection of items. What makes lists special is that they are 'ordered' and 'mutable'.

'Ordered' means that the items in a list have a specific sequence, and this sequence will not change unless you explicitly modify it. Each item in the list has an 'index', which is its position. Indices in Python start from 0 for the first item, 1 for the second, and so on.

'Mutable' means that you can change, add, or remove items from a list after it has been created. This flexibility is incredibly powerful for managing data dynamically.

Let's see how to create a list:

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed_list = ["hello", 10, True, 3.14]
empty_list = []

As you can see, lists can hold items of the same data type (like fruits and numbers) or different data types (like mixed_list). An empty list can also be created.

Accessing items in a list is done using their index. You use square brackets [] with the index number inside.

fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # Output: apple
print(fruits[1])  # Output: banana
チャプターへ戻る