Understanding Python Collections: List, Tuple, and Dictionary

Python

Introduction

Working with collections is a core part of programming in Python. Whether you’re storing a list of items, grouping key-value pairs, or dealing with fixed data, Python provides three main types: lists, tuples, and dictionaries. This article breaks down their differences and shows you when and how to use each.

List: Ordered and Mutable

A list is a flexible, ordered collection that can be modified after creation. Use lists when you need to store a sequence of items and expect to add or remove elements.

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

Lists maintain the order of insertion and can contain duplicates and mixed data types.

Tuple: Ordered and Immutable

A tuple is similar to a list, but immutable—meaning it cannot be changed after it’s created. Use tuples when you want to protect data from being modified.

dimensions = (1920, 1080)
print(dimensions[0])

Tuples are often used for fixed data sets or to represent coordinates and return multiple values from functions.

Dictionary: Key-Value Pairs

A dictionary stores data as key-value pairs. It’s ideal for cases where you want to associate a label (key) with a value.

person = {"name": "Alice", "age": 30}
print(person["name"])
person["city"] = "Tokyo"

Dictionaries are unordered in older versions of Python but preserve insertion order in Python 3.7 and above.

Comparison Table

TypeOrderedMutableUse Case
ListYesYesFlexible sequences
TupleYesNoFixed data
DictionaryYes (3.7+)YesKey-based lookup

Conclusion

Understanding how to choose between lists, tuples, and dictionaries can make your Python code more readable, efficient, and reliable. Practice using each collection in small projects to get comfortable with their differences.

Related Articles

Comment

Copied title and URL