Fundamentals 8 min read

Common Python Data Structures: List, Tuple, Set, and Dictionary

This article introduces Python's four fundamental data structures—list, tuple, set, and dictionary—explaining their characteristics, creation syntax, and typical operations to help readers choose the appropriate structure for different programming scenarios.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Common Python Data Structures: List, Tuple, Set, and Dictionary

Python is a powerful and easy‑to‑learn language that provides several built‑in data structures for organizing and storing data. This article explores the four most common structures—list, tuple, set, and dict—detailing their characteristics, creation syntax, and typical operations.

1. List

A list is an ordered, mutable sequence that can contain elements of different types.

Key Features

Ordered collection: elements stored in insertion order

Mutable: can be modified after creation

Can hold any data type

Allows duplicate elements

Creating a List

fruits = ['apple', 'banana', 'cherry']
numbers = [1, 2, 3, 4, 5]
mixed = [1, 'hello', 3.14, True]

Common Operations

# Access element
print(fruits[0])  # output: apple

# Modify element
fruits[1] = 'blueberry'

# Add elements
fruits.append('orange')  # append at end
fruits.insert(1, 'mango')  # insert at position 1

# Delete elements
del fruits[2]  # delete by index
fruits.remove('apple')  # delete by value
popped = fruits.pop()  # remove and return last element

# Slice
print(numbers[1:3])  # output: [2, 3]

# Length
print(len(fruits))  # current length

2. Tuple

A tuple is similar to a list but immutable; once created it cannot be modified.

Key Features

Ordered collection

Immutable: cannot change after creation

Typically used for data that should not change

Generally faster than lists

Creating a Tuple

colors = ('red', 'green', 'blue')
single_element = (42,)  # note the trailing comma
empty_tuple = ()

Common Operations

# Access element
print(colors[1])  # output: green

# Tuple unpacking
a, b, c = colors
print(b)  # output: green

# Using a tuple to return multiple values
def get_dimensions():
    return 100, 200

width, height = get_dimensions()

3. Set

A set is an unordered collection of unique elements, useful for membership testing and deduplication.

Key Features

Unordered collection

Elements are unique; duplicates are automatically removed

Mutable (frozenset is the immutable version)

Supports mathematical set operations

Creating a Set

vowels = {'a', 'e', 'i', 'o', 'u'}
numbers = set([1, 2, 3, 4, 5])
empty_set = set()  # cannot use {} because that creates an empty dict

Common Operations

# Add element
vowels.add('y')

# Remove element
vowels.remove('a')  # raises KeyError if not present
vowels.discard('b')  # does nothing if element is absent

# Set algebra
a = {1, 2, 3}
b = {2, 3, 4}
print(a | b)  # union: {1, 2, 3, 4}
print(a & b)  # intersection: {2, 3}
print(a - b)  # difference: {1}
print(a ^ b)  # symmetric difference: {1, 4}

4. Dictionary

A dictionary is Python's mapping type, storing key‑value pairs where keys must be immutable.

Key Features

Collection of key‑value pairs

Unordered (maintains insertion order since Python 3.7)

Keys must be unique and immutable (e.g., strings, numbers, tuples)

Values can be of any type

Creating a Dictionary

person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
grades = dict(math=90, physics=85, chemistry=88)
empty_dict = {}

Common Operations

# Access element
print(person['name'])  # output: Alice

# Modify / add element
person['age'] = 26  # modify
person['job'] = 'Engineer'  # add

# Delete element
del person['city']
popped_value = person.pop('age')

# Useful methods
print(person.keys())   # all keys
print(person.values()) # all values
print(person.items())  # all key‑value pairs

# Safe access with default
print(person.get('country', 'USA'))  # returns 'USA' if key missing

# Dictionary comprehension
squares = {x: x*x for x in range(1, 6)}

Data Structure Comparison and Selection

Data Structure

Ordered?

Mutable?

Element Requirements

Main Use Cases

List

Yes

Yes

None

Store ordered collections

Tuple

Yes

No

None

Store data that should not change

Set

No

Yes

Hashable, unique

Deduplication, membership tests, set operations

Dictionary

No (ordered since 3.7)

Yes

Keys must be hashable

Key‑value mapping

Practical Recommendations

Need to preserve order and may modify: use a list.

Need to preserve order but never modify: use a tuple.

Need fast membership testing or deduplication: use a set.

Need a key‑value mapping: use a dictionary.

Large data volume requiring efficient look‑ups: consider dictionaries or sets.

By mastering these four basic data structures, you can organize and manipulate data more effectively in Python and lay a solid foundation for writing more complex and efficient code.

Pythondata structureslistfundamentalsdictionarytupleset
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.