Tuples and Sets

Tuples are very similar to a list however they have one key difference of immutability meaning grabbing an element and reassigning it to a different value is not possible in tuples. Instead of square braces([ ]) , tuples use parenthesis to store objects. A tuple looks something like this :


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

You might be asking yourself, Why use tuples when lists are a much better alternative(in terms of flexibility)? As you begin learning python, you won't be using tuples much however when you become an advanced programmer, you'll start to realize its importance. For instance , tuples will be a preferred choice when you want to store data that remains constant throughout the code so that reassignment of objects is not possible even by a mistake. Operations like indexing and slicing remains the same , also function like len() and methods like find() ,count() ,index() are applicable to both the data structure. Let us run a code where we perform slicing and indexing.

# tuples an easily store multiple datatype objects
my_tuple = ( 1, 'one' , 2 ,'two')
# slicing and index remains the same
print(my_tuple[0])
print(my_tuple[0::])
print(len(my_tuple))
output:
1
(1, 'one', 2, 'two')
4 

Let us take a example where we use methods like index() and count() in tuples :

my_tuple = ( 'a','b','a','a' )
print(my_tuple.index('a'))
print(my_tuple.count('a'))
print(my_tuple.count('b'))
output:
my_tuple = ( 'a','b','a','a' )
print(my_tuple.index('a'))
print(my_tuple.count('a'))
print(my_tuple.count('b'))
Note that while using the index() method , if the data structure has multiple objects similar to the value passed inside the parenthesis , than by default the lowest index of that object will be returned.
my_tuple = (1,2,3)
my_tuple[0] = 2

Reassignment of objects in tuples is not possible.
my_list = [1,2,3]
my_list[0] = 2

Reassignment of objects in lists is possible.
Sets

Sets are unordered collection of Unique objects meaning there can be only be one representative of the same object. A set can be declared in the following way :

  • my_set = set()

Before we proceed to examples , note that the method add() is used to add elements to the set.

my_set = set()
my_set.add(1)
print(my_set)
# if you add 1 again to set , it will still contain only one 1.
# sets only contain unique elements
my_set.add(1)
print(my_set)
output:
{1}
{1}
Sets are very useful when you want a list to only contain unique objects and get rid of the repetitive ones. To cast a list to a set simply write set and pass in the list within the parenthesis in the following way : set(my_list)

Let us understand this with the help of an example.

my_list = [1,1,1,2,2,3,3,3]
my_set = set(my_list)
print(my_set)
output:
{1, 2, 3}




Popular Tutorials

Creative Commons Licence
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.