Complex Data Types in Python
We've already familiarized ourselves with simple (scalar) data types in Python. Now it's time to move on to more powerful tools — complex (composite) data types, which allow us to store and process collections of values.
What are complex data types?
Unlike simple data types (numbers, strings, boolean values) that store a single value, complex types can contain multiple values of various types under one name. They are similar to containers or collections where you can organize and store related data.
Python offers four main complex data types:
- Lists (list) — ordered, mutable collections of elements
- Tuples (tuple) — ordered, immutable collections of elements
- Sets (set) — unordered collections of unique elements
- Dictionaries (dict) — collections of key-value pairs
Let's look at a brief example of each type:
Python 3.13# List (ordered, mutable) fruits = ["apple", "banana", "cherry"] # Tuple (ordered, immutable) coordinates = (10.5, 20.7, 30.9) # Set (unordered, unique elements only) unique_numbers = {1, 2, 3, 4, 5} # Dictionary (key-value pairs) person = {"name": "Alex", "age": 30, "city": "New York"}
Comparison of complex data types
Key differences between the main complex data types:
Note: an empty pair of curly braces {} creates an empty dictionary, not an empty set. To create an empty set, use set().
When to use different data types?
The choice of an appropriate data type depends on the task:
-
List (list) — when the order of elements is important and the collection may change
Python 3.13# Daily to-do list todo_list = ["Buy groceries", "Walk the dog", "Write code"] -
Tuple (tuple) — when data should not change and order is important
Python 3.13# Point coordinates in 3D space point_3d = (10.5, 8.3, 9.1) -
Set (set) — when you only need unique elements and order doesn't matter
Python 3.13# Unique user names unique_users = {"alice", "bob", "charlie"} -
Dictionary (dict) — when data is organized as key-value pairs
Python 3.13# User information user = {"username": "alex123", "email": "alex@example.com", "active": True}
Converting between types
Python makes it easy to convert data from one complex type to another:
Python 3.13# Create a list my_list = [1, 2, 3, 3, 4, 5] # Convert list to tuple my_tuple = tuple(my_list) # (1, 2, 3, 3, 4, 5) # Convert list to set (duplicates will be removed) my_set = set(my_list) # {1, 2, 3, 4, 5} # Create a dictionary from a list of pairs pairs = [("a", 1), ("b", 2), ("c", 3)] my_dict = dict(pairs) # {"a": 1, "b": 2, "c": 3}
Understanding Check
Let's check how well you've understood the basic complex data types:
Which data type is best suited for storing unique elements when order doesn't matter?
In the following lessons we'll explore each of these types in detail. Let's start with lists, the most flexible and frequently used complex data type.
