Python Sets and Tuples


Tuples

Tuples are a set of arranged, immutable (unchangeable), and parenthesized elements   (). A tuple's contents cannot be changed once it has been generated. A tuple's individual elements can be accessed using their respective index values. When grouping together relevant data, tuples are frequently utilized.

 

Sets

Sets and basically collections of unordered elements which are unique and are surrounded by curly braces {}. There are no duplicate values for sets, whereas tuples can have duplicate values. The basic commands to add or remove element is by using add() and remove() methods.

 

Syntax of Sets and Tuples

 

Sets

The syntax for sets with empty values is :

empty_set = set()

 

The syntax for sets with initial values is :

my_set = {1, 2, 3}

 

Tuple

 

The tuple is enclosed in parentheses () and each item is separated by a comma.

my_tuple = (item1, item2, item3, ..., itemN)

 

How  to create a list and tuple in Python

 

Steps To Create Tuple

 

Step 1: Declare and assign a variable to a tuple of values enclosed in parentheses ().

fruits = ('apple', 'banana', 'orange')

 

Step 2: You can access individual elements of the tuple using their index values. Indexing starts from 0 for the first element, 1 for the second, etc.

print(fruits[0])  # Output: 'apple'

print(fruits[1])  # Output: 'banana'

print(fruits[2])  # Output: 'orange'

 

Step 3: You cannot modify the contents of a tuple, since it's immutable(not changeable).

fruits.append('grape')  # Raises an AttributeError

 

 

Steps To Create Sets

 

Step 1: Initialize an empty set

my_set = set()

Note: Using curly braces {} will create an empty dictionary, not an empty set.

 

# Step 2: Add elements to the set

my_set.add(1)

my_set.add(2)

my_set.add(3)

 

# Print the set with initial values

print(my_set)

Output

{1, 2, 3}

 



Thanks for feedback.



Read More....
Arrays and Lists in Python
Python Iterators
Lambda or Anonymous Functions in Python
Most common built-in methods in Python
Python Decorators
Python Dictionaries