Data Types

Lists, Tuples, Dictionaries, and Sets

Explore the key Python data types including lists tuples dictionaries and sets. Understand their properties such as mutability and uniqueness. Learn how to create update and use each type through examples to effectively manage data in Python.

List vs tuple vs dictionary vs set data types

Lists are mutable sequences in Python, meaning they allow for dynamic changes. In contrast, tuples are immutable (fixed collections) that can’t be changed. Dictionaries store key-value pairs and allow for fast lookups, while sets are unordered collections of unique elements.

In highly simplistic terms, lists are like dynamic containers that you can change, tuples are fixed containers you can’t change, dictionaries are similar to labeled boxes used for quick searches, and sets are like unique bags where each item is different.

These data types also have varying syntax.

List syntax

Let’s create a sample list, update it, and print it.

random_list = [17, 5.5, 17, "This is an element in a list", "Hello!", True, None] print(random_list) random_list[0] = 10 print("List after updation:", random_list)

List syntax in Python

Tuple syntax

Let’s create a sample tuple, try to update it, and print it.

random_tuple = (12, "How is your Python Journey going?", False, True, 25.6, 25.6) print(random_tuple) # comment the line below to remove the error random_tuple[0] = 20 print(random_tuple)

Tuple syntax in Python

Note: Since tuples are immutable, you can’t change their elements once they’re created. The above code will therefore result in an error.

Dictionary syntax

Let’s create a sample dictionary, update it, and print it.

random_dict = {"key1": "value1", "key2": 42, "key3": True} print(random_dict) random_dict["new_key"] = "Hope you're learning well!" print("Dictionary after updation:", random_dict)

Dictionary syntax in Python

Set syntax

Let’s create a sample set, update it, and print it.

random_set = {1, 2, 3, 4} print(random_set) random_set.add(1) print("Set after updation: ", random_set)

Set syntax in Python

After adding 1, random_set does not contain two instances of “1” since sets only contain unique elements.

On this page

    In This Module