Tuples, Sets, and Dictionaries

1. Tuples

Tuples are sequence types in Python just like the Lists. But the difference is that instead of square brackets, parenthesis is used to enclose the sequence. Also, tuples are immutable, as the values cannot be changed. But the elements can be accessed with the index. 

Example

				
					tup1 =('physics', 'chemistry', 1997, 2000)

tup2 = (1,2,3,4,5,6,7)

print(tup1[0])

print(tup2[1])
				
			
				
					physics

2
				
			

 2. Sets

Sets are also sequences with immutable values. But the items can be added and removed with sets. Set is represented using the curly brackets

Example

				
					set1  = {1,5,7,9,3}

print("initial set: ", set1)

set1.discard(5)

print("after discarding 5:", set1)
				
			
				
					initial set:  {1, 3, 5, 7, 9}

after discarding 5: {1, 3, 7, 9}
				
			

 Set Operations

3. Set Union

Displays all the elements from both sets. 

Example

				
					A = {1,2,3,4,5}

B = {4,5,6,7,8}

print("the union ", A | B)
				
			
				
					the union  {1, 2, 3, 4, 5, 6, 7, 8}
				
			

 4. Set Intersection

Displays the common elements from the given sets.

Example

				
					A = {1,2,3,4,5}

B = {4,5,6,7,8}

print("the intersection: ", A & B)
				
			
				
					the intersection:  {4, 5}
				
			

5. Dictionaries

Dictionary is a collection of ordered, and changeable values. Data is stored as a pair  (key:value).

Example

				
					dict = {1:'alphabets', 2:'for', 3:'study'}

print(dict)
				
			
				
					{1: 'alphabets', 2: 'for', 3: 'study'}
				
			

6. Dictionary Operations

Look at the following operations done on the dictionary.

Example

				
					dict = {1:'alphabets', 2:'for', 3:'study'}

temp = dict[3]

print("value of the key is:", temp)
				
			
				
					value of the key is: study