Python Tuples and Sets

Hey friends 👋 welcome back, In the last lesson, we learned about lists, Today, we are going to learn about tuples and sets, which are other ways to store multiple values in Python, Tuples and sets are useful for different situations depending on whether you want fixed items or unique items.

Python Tuples

A tuple is similar to a list but cannot be changed after it is created, This is called immutable, Example:

coordinates = (10, 20) fruits = ("apple", "banana", "mango") print(coordinates) print(fruits[1])

Output:

(10, 20) banana
  • You cannot change a tuple item once it is created

  • Tuples are useful when you want data to remain constant

Python Sets

A set is a collection of unique items and does not keep order, Example:

colors = {"red", "green", "blue"} colors.add("yellow") colors.remove("green") print(colors)

Output Example (order may vary):

{'red', 'blue', 'yellow'}
  • Sets automatically remove duplicates

  • You cannot access items by index in a set because they are unordered

Converting Between Lists, Tuples, and Sets

You can convert between these types using list(), tuple(), and set(), Example:

fruits = ["apple", "banana", "apple"] fruit_set = set(fruits) # removes duplicates fruit_tuple = tuple(fruit_set) fruit_list = list(fruit_tuple) print(fruit_list)

Practice Time

Create a Python file called tuples_sets.py and try these exercises, 1, Create a tuple with three numbers and print the second number, 2, Create a set with five colors and add a new color, 3, Remove a color from your set and print it, 4, Convert a list with duplicates into a set to remove duplicates, then convert it back to a list

Great job, You just learned how to store multiple values in Python using tuples and sets, In the next lesson, we will explore Python Dictionaries, where we will learn how to store data in key-value pairs, We will soon be launching our YouTube channel, where we are going to post step-by-step video tutorials on Python and other tech skills, These videos will make learning easier and more visual, helping beginners follow along confidently.