Bytes

Tuples and Sets in Python

Module - 4 Data Structures in Python
Tuples and Sets in Python

Overview:

Tuples and sets are both data structures in Python. Tuples are ordered collections of elements, which are immutable (meaning they can't be changed once created). Sets, on the other hand, are unordered collections of unique elements.

Tuples and Sets in Python-min.png

What is a Tuple in Python?

The POS system may have a tuple that contains the details of each order made by a customer. This tuple may include the customer's name, the items ordered, the quantities ordered, and the total cost of the order.

In Python, a tuple could be a data type comparable to a list but immutable, meaning it cannot be changed once made. A tuple is made by enclosing a sequence of values in parentheses, separated by commas.

Tuples can be utilized in Python in a restaurant's point-of-sale (POS) framework. Tuples can be created by placing elements inside parentheses, separated by commas. For example, a tuple of three elements could be created like this: (1," hello", True). Once created, the elements of a tuple can be accessed using indexing, just like with lists.

The Syntax of Tuple:

variable_name=(tuple elements separated by comma)

Example:

order = ("John Smit", "Hamburgers", 2, 15.0, "French Fry", 1, 5.0, 35.0)

In this example, the tuple contains the following information:

  • The customer's name is "John Smith".
  • The customer ordered 2 hamburgers at the cost of $15.00 each.
  • The customer also ordered 1 serving of French fry for $5.00.
  • The total cost of the order is $35.00.

Once the order is created, the tuple is immutable and cannot be changed. This means that the details of the order cannot be accidentally or maliciously altered by an employee. Tuples can also create more complex data structures, such as a list of orders or a dictionary that maps customer names to their orders.

How to Access Elements of Tuple?

In Python, you'll be able to get to elements of a tuple utilizing indexing. The indexing begins for the first element, 1 for the second element, and so on. To get to a tuple component, you can utilize square brackets [] with the index of the element you need to access. For illustration:

my_tuple = (1, 2, 3, 4, 5)

# Accessing the first element of the tuple
print(my_tuple[0]) # Output: 1

# Accessing the third element of the tuple
print(my_tuple[2]) # Output: 3

You can also use negative indexing to access elements from the end of the tuple. The index -1 refers to the last element, -2 refers to the second last element, and so on. For example:

my_tuple = (1, 2, 3, 4, 5)

# Accessing the last element of the tuple
print(my_tuple[-1]) # Output: 5

# Accessing the second last element of the tuple
print(my_tuple[-2]) # Output: 4

You can also use slicing to access a range of elements in a tuple. Slicing creates a new tuple that contains the specified range of elements. You can use the colon: operator to slice a tuple with the start and end indices of the range you want to slice. For example:

my_tuple = (1, 2, 3, 4, 5)

# Slicing the tuple to get elements from index 1 to 3 (excluding 3)
sliced_tuple = my_tuple[1:3]

print(sliced_tuple) # Output: (2, 3)

ūüí° Note that tuples are immutable objects, meaning you cannot modify the elements of a tuple once it is created. If you try to modify a tuple, Python will raise a TypeError.

What is Set in Python?

In Python, a set is a collection of unique elements that are unordered and mutable. One industry example of using sets in Python is data analysis. For instance, suppose a data analyst is working with a large dataset of customer transactions from an e-commerce platform. The analyst needs to extract a list of unique products that customers purchase during a specific time period. 

Here, the analyst can use a Python set to efficiently extract a list of unique products. The analyst can create a set and iterate through each transaction in the dataset. The analyst can extract and add the product ID to the Set for each transaction. Since sets only allow unique elements, the Set will automatically remove duplicates. 

Sets are created by placing elements inside curly braces, separated by commas. For example, three elements could be created: {1, 2, 3}. If there are duplicates in the Set, they are automatically removed. The elements of a set can also be accessed using iteration or various built-in methods. 

Syntax for Set:

variable_name=(set elements separated by comma)

Example:

# Using curly braces
my_set = {1, 2, 3, 4, 5}

# Using set() function
my_set = set([1, 2, 3, 4, 5])

Operations on Sets:

You can use the add() method to add elements to a set. You can use the remove() or discard() method to remove an element. For example:

my_set = {1, 2, 3}

my_set.add(4) # Add element 4 to the set
my_set.remove(3) # Remove element 3 from the set
my_set.discard(2) # Remove element 2 from the set (if it exists)

We can also perform various set operations, such as union, intersection, and difference, using the |, &, and - operators, respectively. For example:

set1 = {1, 2, 3}
set2 = {3, 4, 5}

union = set1 | set2 # Union of set1 and set2 (elements in either set)
intersection = set1 & set2 # Intersection of set1 and set2 (elements in both sets)
difference = set1 - set2 # Difference of set1 and set2 (elements in set1 but not in set2)

How to Access Elements from set?

In Python, you can access elements of a set by looping through the Set or by using the in keyword to check if an element is in the Set. To loop through a set, you can use a for loop. For example:


my_set = {1, 2, 3, 4, 5} 
for element in my_set: 
    print(element)

To check if an element is in the Set, you can use the i keyword. For example:


my_set = {1, 2, 3, 4, 5} 
if 3 in my_set: 
    print("3 is in the set") 
else:
    print("3 is not in the set")

You convert a set to a list or a tuple and access elements by index. In any case, since sets are unordered, the order of elements within the list or tuple isn't ensured to be the same as the order of elements within the Set. Hence, for the most part, it's not suggested to get to components of a set by index.

Which one is better to use Set or Tuple?

Tuples are an immutable collection of variables, while sets are mutable collections of variables. Which do you think makes the better choice? Tuples are immutable collections of variables, so they can't be changed after creation. Sets are mutable collections of variables, so sets  can be changed after creation. The better choice is set because it allows us to add or remove items  while the Set is in use.

Conclusion

In summary, tuples and sets are valuable data structures in Python, each with unique properties and use cases. Understanding their differences allows you to choose the right one for your needs and write more efficient, effective code.

Key Takeaways

  • This lesson provides an introduction to tuples and sets in Python.
  • Tuples are ordered collections of immutable elements, while sets are unordered collections of unique elements.
  • The lesson clarifies how to create, access, and modify tuples and sets and the operations that can be performed on them.
  • It also discusses the contrasts between tuples and sets and when to utilize each.

Quiz

  1. Which of the following is true about tuples in Python? 
    1. Tuples are immutable  
    2. Tuples are mutable 
    3. Tuples are ordered 
    4. Tuples can contain duplicate elements

Answer: a. Tuples are immutable

  1. What is the syntax to create a tuple in Python? 
    1. variable_name=[tuple elements separated by comma]  
    2. variable_name=(tuple elements separated by comma) 
    3. variable_name{tuple elements separated by comma} 
    4. variable_name tuple elements separated by comma

Answer: b. variable_name=(tuple elements separated by comma)

  1. How can you access the first element of a tuple? 
    1. Using the index 0  
    2. Using the index 1  
    3. Using the index -1 
    4. Using the index -2

Answer: a. Using the index 0

  1. Which of the following is true about sets in Python? 
    1. Sets are ordered 
    2. Sets are immutable 
    3. Sets can contain duplicate elements 
    4. Sets are unordered and contain unique elements

Answer: d. Sets are unordered and contain unique elements

  1. What is the syntax to create a set in Python?  
    1. variable_name=[set elements separated by comma] 
    2. variable_name=(set elements separated by comma) 
    3. variable_name{set elements separated by comma} 
    4. variable_name={set elements separated by comma}

Answer: d. variable_name={set elements separated by comma}

Recommended Courses
Certification in Full Stack Data Science and AI
Course
20,000 people are doing this course
Become a job-ready Data Science professional in 30 weeks. Join the largest tech community in India. Pay only after you get a job above 5 LPA.
Masters in CS: Data Science and Artificial Intelligence
Course
20,000 people are doing this course
Join India's only Pay after placement Master's degree in Data Science. Get an assured job of 5 LPA and above. Accredited by ECTS and globally recognised in EU, US, Canada and 60+ countries.

AlmaBetter’s curriculum is the best curriculum available online. AlmaBetter’s program is engaging, comprehensive, and student-centered. If you are honestly interested in Data Science, you cannot ask for a better platform than AlmaBetter.

avatar
Kamya Malhotra
Statistical Analyst
Fast forward your career in tech with AlmaBetter

Vikash SrivastavaCo-founder & CPTO AlmaBetter

Vikas CTO

Related Tutorials to watch

Top Articles toRead

AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2023 AlmaBetter