Python Tutorial #3: Lists, Tuples and sets

Published on: 08 Sept. 2024

Category: python tutorial


Lists

A list in Python is a data structure used to store collections of elements in a specific order. The elements in a list can be of any type, including numbers, strings, other lists, and other objects. A list is mutable, which means its elements can be modified after creation.


my_list = [1, 2, 3, 4, 5]
another_list = ["apple", "banana", "cherry"]
mixed_list = [1, apple, True, 3.14]
                                        

Tuples

A tuple in Python is a data structure similar to a list but with one key difference: tuple elements are immutable. This means that once a tuple is created, you cannot change, add, or remove elements from it. Tuples are used when you want to group data and ensure that it cannot be modified.


my_tuple = (1, 2, 3)
another_tuple = ("apple", "banana", "cherry")
mixed_tuple = (1, "apple", True, 3.14)
                                        

Sets

A set in Python is a collection of unique elements without a specific order. Unlike lists and tuples, sets do not allow duplicate elements, and their elements have no defined order. These characteristics make sets ideal for situations where you need to store unique values and perform fast operations like unions, intersections, and differences.


my_set = {1, 2, 3, 4}
another_set = {"apple", "banana", cherry"}
empty_set = set()