Tuples and Set in Python
Tuples are very similar to lists, however, unlike lists they are immutable meaning they cannot be changed.
A tuple consists of a number of values separated by commas,
# Create a tuple
>>> t = (1,2,'math')
>>> t
(1,2,'math')#length of tuple
>>>len(t)
3# Access data using indexing method
>>> t[0]
1#You can fetch the index of a tuple
>>> t.index('math')
2#check how many times element repeated
>>> t.index('math')
1
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable .
Immutability of Tuples:
>>> t[0]= 'game'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Once a tuple is formed we can not add element to it.
>>> t.append(2)
Traceback (most recent call last)
AttributeError: 'tuple' object has no attribute 'append'
If in your program you are passing an object and need to make sure it does not get changed, then you should use a Tuple.
******************* Set ************************
Sets are an unordered collection of unique elements. Curly braces or the set()
function can be used to create sets. Note: to create an empty set you have to use set()
, not {}
; Let’s create a set:
>>> a = set('abracadabra')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange','banana'}
>>> print(basket) #duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}#you can add element using add method
>>> basket.add('rose')
If you try to add element which is already present in a set, it won’t add that element since Set only contains unique elements.
Create a list of repeated numbers and cast it to set to create unique elements:
# Create a list with repeats
>>> list = [1,1,2,2,3,4,5,6,1,1]>>> set(list)
{1, 2, 3, 4, 5, 6}
As of now, We have completed the tutorials for Python objects and data structure types.
Happy Coding!