. List, Sets, Tuple & Dictionary Operations

[2]:
12345
# accessing element in a nested list 
sample_list = [["Hello","world"],["we are learning python"]]
print(sample_list[0][1])
print(sample_list[0][1][:3])
stdout
world wor
[3]:
1234
# get 3rd elment from the last in a list
sample_list = [20,21,22,23,24,25]
print(sample_list[-3])
stdout
23
[4]:
12
# length of a list 
len(sample_list)
Out[4]:
6
[5]:
1234
# adding an element to a list
print(f"list before adding an element {sample_list}")
sample_list.append('a')
print(f"list after adding an element {sample_list}")
stdout
list before adding an element [20, 21, 22, 23, 24, 25] list after adding an element [20, 21, 22, 23, 24, 25, 'a']
[6]:
1234
# if you want to add element at any specific index (provide index and the value) all the values will be shifted to right of 
# the list 
sample_list.insert(0,'b')
sample_list
Out[6]:
['b', 20, 21, 22, 23, 24, 25, 'a']
[7]:
1234
# concateing two list
list1 = ['a','b','c']
list2 = ['d','e','f']
print(list1+list2)
stdout
['a', 'b', 'c', 'd', 'e', 'f']
[8]:
1234
# reversing a list
print(list1[::-1]) # method 1
list1.reverse() # method 2 actual string will be changes 
print(list1)
stdout
['c', 'b', 'a'] ['c', 'b', 'a']
[11]:
1234
# remove an element from list
list1=['a','b','c']
list1.remove('c')
list1
Out[11]:
['a', 'b']
[13]:
12345678
# remove element using pop method
list1=['a','b','c']
list1.pop() # pop is used without index last element will be removed 
print(list1)
list1=['a','b','c']
list1.pop(0) # pop is used without index last element will be removed 
print(list1) # if pop is used with index the element of index will be removed
stdout
['a', 'b'] ['b', 'c']
[15]:
12345
# slicing dicing a list 
list1=['a','b','c',1,2,3,4,5]
print(list1[1:]) # get all the element after 1 index inclding 1 
print(list1[:5]) # get all element before 5th index 
print(list1[-4]) # get 4th element from end of the list 
stdout
['b', 'c', 1, 2, 3, 4, 5] ['a', 'b', 'c', 1, 2] 2
[19]:
12345678910
# List comprehension - writing for in a list 
l=[10,9, 1, 2, 3, 4, 5]
for i in l :
    print(i) # instead of this we can wrie below statement
print("Simple list comprehension")
print([i for i in l]) # simple list comprehension 
print("list comprehension with transformations")
print([i*2 for i in l]) # simple list where each element is doubled 
print("list comprehension with transformations and filter")
print([i*2 for i in l if i%2==0]) # list comprehension with filter 
stdout
10 9 1 2 3 4 5 Simple list comprehension [10, 9, 1, 2, 3, 4, 5] list comprehension with transformations [20, 18, 2, 4, 6, 8, 10] list comprehension with transformations and filter [20, 4, 8]
[20]:
123
# nested list comprehension 
l=[[10,9, 1, 2, 3, 4, 5],[10,9, 1, 2, 3, 4, 5],[10,9,4, 5]] # doubling each element of the sublist
[[j*2 for j in i] for i in l]
Out[20]:
[[20, 18, 2, 4, 6, 8, 10], [20, 18, 2, 4, 6, 8, 10], [20, 18, 8, 10]]
[51]:
12
# get the frequency of an element is a list
sample_list.count(22)
Out[51]:
1
[60]:
123456
# arithmatic operations like max , min, sum,len are also possible 
sample_list=[20, 18, 2, 4, 6, 8, 10]
print(sum(sample_list))
print(min(sample_list))
print(max(sample_list))
print(len(sample_list))
stdout
68 2 20
[22]:
1234567
# adding element to a set- since sets are mutable new elements can be added to it, but item assignment is not possible , since 
# sets are unorder

sample_set={1,2,3,5,8,10}
print("Before adding ",sample_set)
sample_set.add('12')
print("After adding ",sample_set)
stdout
Before adding {1, 2, 3, 5, 8, 10} After adding {1, 2, 3, 5, '12', 8, 10}
[27]:
1234
# sets can only have unique value 
sample_set={1,2,3,5,8,10}
sample_set.add(1) # adding 1 again will not duplicate the values in a set
sample_set
Out[27]:
{1, 2, 3, 5, 8, 10}
[31]:
1234
# union operation in sets
sample_set_1={1,2,3,4,5}
sample_set_2={4,5,6,7,8} # notince that 4 and 5 are common in 2 sets 
sample_set_1.union(sample_set_2)# the new set will have all the variables but without duplicates
Out[31]:
{1, 2, 3, 4, 5, 6, 7, 8}
[33]:
1234
# intersection operation in sets
sample_set_1={1,2,3,4,5}
sample_set_2={4,5,6,7,8} # notince that 4 and 5 are common in 2 sets 
sample_set_1.intersection(sample_set_2)# the new set will have all only common variable in 2 sets 
Out[33]:
{4, 5}
[35]:
1234
# finding difference in two sets
sample_set_1={1,2,3,4,5}
sample_set_2={4,5,6,7,8} # notince that 4 and 5 are common in 2 sets 
sample_set_1.difference(sample_set_2)# values in 1 which are not present in set 2
Out[35]:
{1, 2, 3}
[36]:
1234
# Operators with set 
sample_set_1={1,2,3,4,5}
sample_set_2={5,4,3,2,1} # since sets are inordered below 2 sets are equal 
sample_set_1==sample_set_2
Out[36]:
True
[39]:
123456789101112
# inequality, subset and superset can also be checked in sets 
sample_set_1={1,2,3,4,5}
sample_set_2={4,3,2,1} # since sets are inordered below 2 sets are equal 
print("Checking inequality")
print(sample_set_1!=sample_set_2 )# checking inequality in sets

print("Checking subset")
print(sample_set_1<=sample_set_2 )# checking subset

print("Checking superset")
print(sample_set_1>=sample_set_2 )# checking superset
stdout
Checking inequality True Checking subset False Checking superset True
[40]:
1
import random
[47]:
12345678910
sample_tuple=tuple([random.randint(1,100) for x in range(100)])
# tuples are index and slicing dicing like a list is also possible

print(sample_tuple[4]) # access 4th element
print(sample_tuple[4:10]) # access element from index 4 to 10
print(sample_tuple[:10]) # access element from index 0 to 10
print(sample_tuple[10:]) # access element from index 10 to last
print(sample_tuple[::-1]) # reverse a tuple

stdout
10 (10, 49, 65, 80, 71, 97) (84, 46, 73, 52, 10, 49, 65, 80, 71, 97) (66, 53, 75, 26, 90, 7, 36, 6, 99, 39, 100, 15, 59, 86, 12, 26, 66, 36, 69, 75, 68, 36, 30, 63, 37, 91, 37, 17, 97, 60, 48, 18, 60, 95, 23, 55, 37, 9, 31, 56, 57, 91, 78, 28, 92, 13, 38, 59, 100, 47, 50, 61, 83, 32, 40, 45, 95, 64, 17, 95, 24, 46, 20, 97, 90, 73, 47, 48, 9, 20, 39, 32, 95, 97, 67, 48, 1, 95, 63, 8, 10, 64, 66, 13, 55, 14, 84, 78, 13, 91) (91, 13, 78, 84, 14, 55, 13, 66, 64, 10, 8, 63, 95, 1, 48, 67, 97, 95, 32, 39, 20, 9, 48, 47, 73, 90, 97, 20, 46, 24, 95, 17, 64, 95, 45, 40, 32, 83, 61, 50, 47, 100, 59, 38, 13, 92, 28, 78, 91, 57, 56, 31, 9, 37, 55, 23, 95, 60, 18, 48, 60, 97, 17, 37, 91, 37, 63, 30, 36, 68, 75, 69, 36, 66, 26, 12, 86, 59, 15, 100, 39, 99, 6, 36, 7, 90, 26, 75, 53, 66, 97, 71, 80, 65, 49, 10, 52, 73, 46, 84)
[53]:
1234
# concat two tuples 
sample_tuple_1=tuple([random.randint(1,10) for x in range(100)])
sample_tuple_2=tuple([random.randint(1,10) for x in range(100)])
print(len(sample_tuple_1+sample_tuple_2))
stdout
200
[57]:
12345
# get first index of a value in tuple 
print(sample_tuple_1.index(2))

# get freq of an element in a tuple  
sample_tuple_1.count(2)
stdout
5
Out[57]:
10
[61]:
123456
# operations like max , min, sum,len are also possible 
sample_tuple_1=(20, 18, 2, 4, 6, 8, 10)
print(sum(sample_tuple_1))
print(min(sample_tuple_1))
print(max(sample_tuple_1))
print(len(sample_tuple_1))
stdout
68 2 20 7
[64]:
1234
# get all key and values of a dict 
sample_dict={'a':1,'b':2,'c':3,'d':4}
print("Keys -->",sample_dict.keys())
print("values -->",sample_dict.values())
stdout
Keys --> dict_keys(['a', 'b', 'c', 'd']) values --> dict_values([1, 2, 3, 4])
[65]:
1234567
# remove the element using a given key 
print("Before removing element")
sample_dict={'a':1,'b':2,'c':3,'d':4}
print(sample_dict)
print("After removing element")
sample_dict.pop('a')
print(sample_dict)
stdout
Before removing element {'a': 1, 'b': 2, 'c': 3, 'd': 4} After removing element {'b': 2, 'c': 3, 'd': 4}
[67]:
1234567
# iterator over keys and values together
# method 1
for k,v in zip(sample_dict.keys(),sample_dict.values()):
    print(f"For key {k} the value is {v}")

# method 2 using list comprehension
[f"for key {k} the values is {v}" for k,v in sample_dict.items()]
stdout
For key b the value is 2 For key c the value is 3 For key d the value is 4
Out[67]:
['for key b the values is 2', 'for key c the values is 3', 'for key d the values is 4']
[69]:
123456789
# Example 1 - create a dict from a list where keys are values of list and values are count of that value in list
sample_list=[random.randint(1,10) for x in range(100)]
final_dict={}
for i in sample_list:
    if i in final_dict.keys():
        final_dict[i]=final_dict[i]+1
    else:
        final_dict[i]=1
final_dict
Out[69]:
{5: 12, 3: 13, 1: 6, 7: 17, 8: 13, 6: 9, 4: 9, 10: 8, 2: 6, 9: 7}
[72]:
123456789101112
# Example 2 -  Write a Python function to remove duplicates from a list and return the unique elements.
sample_list=[random.randint(1,10) for x in range(100)]
# method 1 - using loop
final_list=[]
for i in sample_list:
    if i in final_list:
        pass 
    else:
        final_list.append(i)

# method 2 - using set 
list(set(sample_list))
Out[72]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[ ]:
1