Tuples and Sets In Python

Tuples 

We saw that lists and strings have many common properties, such as indexing and slicing
operations. They are two examples of sequence data types (see Sequence Types — str, bytes,
bytearray, list, tuple, range). Since Python is an evolving language, other sequence data types
may be added. There is also another standard sequence data type: the tuple.
A tuple consists of a number of values separated by commas, for instance:
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
As you see, on output tuples are always enclosed in parentheses, so that nested tuples are
interpreted correctly; they may be input with or without surrounding parentheses, although often
parentheses are necessary anyway (if the tuple is part of a larger expression).
Tuples have many uses. For example: (x, y) coordinate pairs, employee records from a
database, etc. Tuples, like strings, are immutable: it is not possible to assign to the individual
items of a tuple (you can simulate much of the same effect with slicing and concatenation,
though). 

 

 

 Sets

 
Python  includes a data type for sets. A set is an unordered collection with no duplicate 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 {}; the latter creates an empty dictionary.

However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc.
It can have any number of items and they may be of different types (integer, float, tuple, string etc.).
Note:But a set cannot have a mutable element, like list, set , dictionary  as its element.In set we cannot give lists.


Ex:
# set of integers
1)my_set = {1, 2, 3}
print(my_set)

# set of mixed datatypes
2)my_set = set([1,2,3,2])
print(my_set)
3)my_set = set([1,2,3,2])
print(my_set)

4)sett={1,2,3,2}
print(sett)

Creating a empty set:
a=set()
>>> print a
set([])

Ex:
>>> se={1,[1,2,3],4}

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    se={1,[1,2,3],4}
TypeError: unhashable type: 'list' ..........mix together or mess up

>>> sett={1,2,3}
>>> type(sett)
<type 'set'>

Changing Sets:

# initialize my_set
my_set = {1,3}
print(my_set)

# if you uncomment line 9,
# you will get an error
# TypeError: 'set' object does not support indexing

#my_set[0]

# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)

# add multiple elements
# Output: {1, 2, 3, 4}
my_set.update([2,3,4])
print(my_set)

# add list and set
# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4,5], {1,6,8})
print(my_set)

Remove elements in sets:
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)

# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)

# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)

# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)

# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)

# pop an element
# Output: random element
print(my_set.pop())

# pop another element
# Output: random element
my_set.pop()
print(my_set)

# clear my_set
#Output: set()
my_set.clear()
print(my_set)

SET OPERATIONS:
1) Union:
Union of A and B is a set of all elements from both sets.
Union is performed using | operator. Same can be accomplished using the method union()

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)

# use union function
>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}
 
# use union function on B
>>> B.union(A)
{1, 2, 3, 4, 5, 6, 7, 8}
 
2) Intersection:
Intersection of A and B is a set of elements that are common in both sets.
Intersection is performed using & operator. Same can be accomplished using the method intersection(
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use & operator
# Output: {4, 5}
print(A & B)



# use intersection function on A
>>> A.intersection(B)
{4, 5}
 
# use intersection function on B
>>> B.intersection(A)
{4, 5}
3)
Set Difference:
Difference of A and B (A - B) is a set of elements that are only in A but not in B. Similarly, B - A is a set of element in B but not in A.

>>> A.difference(B)
{1, 2, 3}
 
# use - operator on B
>>> B - A
{8, 6, 7}
 
# use difference function on B
>>> B.difference(A)
{8, 6, 7}
4)
Symmetric Difference
Symmetric Difference of A and B is a set of elements in both A and B except those that are common in both.
Symmetric difference is performed using ^ operator. Same can be accomplished using the method symmetric_difference()

# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
Try the following examples on Python shell.
 
# use symmetric_difference function on A
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}
 
# use symmetric_difference function on B
>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}

Python Frozenset
Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once assigned. While tuples are immutable lists, frozensets are immutable sets.

Frozensets can be created using the function frozenset()
B = frozenset([3, 4, 5, 6])

frozenset({1, 2, 3, 4, 5, 6})
>>> A.add(3)


DICTIONARRY:
Python dictionary is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a key: value pair.
Dictionaries are optimized to retrieve values when the key is known.
Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
An item has a key and the corresponding value expressed as a pair, key: value.
While values can be of any data type and can repeat, keys must be of immutable type string, number or tuple with immutable elements) and must be unique.
# empty dictionary
my_dict = {}
 
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
 
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
 
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
 
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])

Accesing Values and Keys:
my_dict = {'name':'Nikhil', 'age': 27}

# Output: Jack
print(my_dict['name'])

# Output: 26
print(my_dict.get('age'))

# Trying to access keys which doesn't exist throws error
# my_dict.get('address')
# my_dict['address']
 

 

 

Comments

Popular posts from this blog

Linear Regression Numpy code

week 11(21-25 october)

How java is different from c/c++?