Data Structures:
- Allow to organize, manage, and store data efficiently.
Major data structures in Python:
- List
- Tuple
- Set
- Dictionary
List:
- Ordered: The items have a particular order. When we print or access elements, they appear in the same order as we added them.
- Mutable: We can modify their contents by adding, removing, or changing elements after creating the list.
- Allows duplicates: A list can have multiple elements with the same value.
- Indexable: We can access elements by their index.
- Syntax: list_name = [item1, item2, item3, …] & created using square brackets [ ]
#Creating list
fruits = ['apple', 'banana', 'cherry']
print(fruits)
fruits.append('orange') # Add an element
print(fruits)
fruits[1] = 'blueberry' # Modify an element
print(fruits)
Output: ['apple', 'banana', 'cherry'] ['apple', 'banana', 'cherry', 'orange'] ['apple', 'blueberry', 'cherry', 'orange']
Tuple:
- Ordered: Elements have a defined order same as list
- Immutable: Once a tuple is created, you cannot modify its elements.
- Allows duplicates: A tuple can have multiple elements with the same value.
- Indexable: You can access elements by their index.
- Syntax: tuple_name = (item1, item2, item3, …) & created using Parentheses ()
# Creating tuple
fruits = ('apple', 'banana', 'cherry','banana')
print(fruits)
Output: ('apple', 'banana', 'cherry', 'banana')
fruits[1] = 'blueberry' # Modify an element
print(fruits)
Output: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-10-8ffc2ae47528> in <cell line: 1>() ----> 1 fruits[1] = 'blueberry' # Modify an element 2 print(fruits) TypeError: 'tuple' object does not support item assignment
fruits.append('orange') # Add an element
print(fruits)
Output: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-11-f47e141fd874> in <cell line: 1>() ----> 1 fruits.append('orange') # Add an element 2 print(fruits) AttributeError: 'tuple' object has no attribute 'append'
Set:
- Unordered: Elements do not have a specific order. The set may display elements in a different order each time when we access it, and we can’t rely on the order of elements in a set.
- Mutable: We can add or remove elements from a set but we cannot change or modify individual items in a set as unordered.
- No duplicates: A set cannot have multiple elements with the same value.
- Not indexable: We cannot access elements by their index as no order.
- Syntax: set_name = {item1, item2, item3, …} & created using curly braces or curly brackets {}
#Creating set
fruits = {'banana','apple', 'banana', 'cherry'}
print(fruits) # 'banana' will be once in output as set does not allow duplicate
fruits.add('orange') # Add an element
print(fruits)
Output: {'apple', 'cherry', 'banana'} {'apple', 'orange', 'cherry', 'banana'}
fruits[1] = 'blueberry' # Modify an element
print(fruits)
Output: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-16-5fcbd515ff35> in <cell line: 1>() ----> 1 fruits[1] = 'blueberry' # Modify an element 2 print(fruits) TypeError: 'set' object does not support item assignment
Why should we use .append() in List & .add() in set while both are mutable?
The difference between using append() in a list and add() in a set in Python arises from the fundamental differences in how lists and sets work:
1. List & .append():
- Ordered and Indexed: A list is an ordered collection, meaning elements are stored in the order they were added, and each element can be accessed by its index.
- Allowing Duplicates: Lists can have duplicate elements.
- Operation:
- append(item) is used to add an element to the end of the list, maintaining the order of elements.
2. Set & .add():
- Unordered and Unindexed: A set is an unordered collection, meaning there is no specific order, and an index cannot access elements.
- Unique Elements: Sets automatically enforce uniqueness, meaning no two elements in a set can be the same.
- Operation:
- add(item) is used to add an element to a set. Since the set does not maintain order and does not allow duplicates, the element is simply added if it is not already present.
Dictionary:
- Key-value pairs: A dictionary is a collection of key-value pairs. Each key is unique, and it maps to a value.
- Unordered: (as of Python 3.7, dictionaries maintain the insertion order).
- Mutable: You can add, remove, or modify key-value pairs.
- Keys are unique: No two keys can have the same value.
- Indexable by keys: You access elements using their keys.
- Syntax: dict_name = {key1: value1, key2: value2, …} & created using curly braces or curly brackets {}
#Creating dictionary
person = {'name': 'Rana', 'age': 40, 'city': 'Dhaka','age': 12} # Python will only keep the last key-value pair, and the earlier one will be overwritten.
print(person)
person['age'] = 35 # Modify a value
print(person)
person['job'] = 'Data Scientist' # Add a new key-value pair
print(person)
Output: {'name': 'Rana', 'age': 12, 'city': 'Dhaka'} {'name': 'Rana', 'age': 35, 'city': 'Dhaka'} {'name': 'Rana', 'age': 35, 'city': 'Dhaka', 'job': 'Data Scientist'}
How to know the number of items in these data structures:
- We can use len() to know the number of data structures
person = {'name': 'Rana', 'age': 40, 'city': 'Dhaka','age': 12}
fruits = {'banana','apple', 'cherry'}
numbers = (1, 2, 3, 4, 4, 5)
city = ['dhaka','delhi', 'lahore']
print(len(person))
print(len(fruits))
print(len(numbers))
print(len(city))
Output: 3 3 6 3
How to know the type of data structures:
- We can use type() to know the number of data structures
person = {'name': 'Rana', 'age': 40, 'city': 'Dhaka','age': 12}
fruits = {'banana','apple', 'cherry'}
numbers = (1, 2, 3, 4, 4, 5)
city = ['dhaka','delhi', 'lahore']
print(type(person))
print(type(fruits))
print(type(numbers))
print(type(city))
Output: <class 'dict'> <class 'set'> <class 'tuple'> <class 'list'>
Access Items:
- List items are indexed and we can access them by referring to the index number
#Access list
animals = ['cow','goat','lamb',"buffelo","camel"]
animals[2]
Output: lamb
- Tuple items are indexed and we can access them by referring to the index number
#Access tuple
animals = ('cow','goat','lamb',"buffelo","camel")
animals[2]
Output: lamb
- Set unordered so we cannot access items in a set by referring to an index or a key.
- But we can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.
#Access set
animals = {'cow','goat','lamb',"buffelo","camel"}
animals[2]
Output: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-34-1f636996566c> in <cell line: 3>() 1 animals = {'cow','goat','lamb',"buffelo","camel"} 2 ----> 3 animals[2] TypeError: 'set' object is not subscriptable
#Access set by for loop
animals = {'cow','goat','lamb',"buffelo","camel"}
for animal in animals:
print(animal)
Output: camel goat buffelo cow lamb
- Dictionary has key-value so we can access the items of a dictionary by referring to its key name, inside square brackets.
#Access dictionary
person = {'name': 'Rana', 'age': 40, 'city': 'Dhaka'}
person['city']
Output: Dhaka
Change Item Value:
- List are Indexable, we can change value of list by its index number
animals = ['cow','goat','lamb',"buffelo","camel"]
animals[1]= 'tiger'
print(animals)
Output: ['cow', 'tiger', 'lamb', 'buffelo', 'camel']
- Tuple is Indexable but immutable we cannot change the value of tuple by its index number
- But we can change tuple to list , after that change value & then re-change to tuple
animals = ('cow','goat','lamb',"buffelo","camel")
animals[3]= 'Lion'
print(animals)
Output: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-44-10ea32d731b3> in <cell line: 3>() 1 animals = ('cow','goat','lamb',"buffelo","camel") 2 ----> 3 animals[3]= 'Lion' 4 5 print(animals) TypeError: 'tuple' object does not support item assignment
animals = ('cow','goat','lamb',"buffelo","camel")
animals = list(animals) # Convert to list
animals[2]= 'Lion' # change item
animals = tuple(animals) # convert to tuple
print(animals)
Output: ('cow', 'goat', 'Lion', 'buffelo', 'camel')
- Sets are unordered, so we cannot change or modify individual items
- Instead we can add & remove to make this change
animals = {'cow','goat','lamb',"buffelo","camel"}
animals[3]= 'Lion'
print(animals)
Output: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-48-26a7feced54c> in <cell line: 3>() 1 animals = {'cow','goat','lamb',"buffelo","camel"} 2 ----> 3 animals[3]= 'Lion' 4 5 print(animals) TypeError: 'set' object does not support item assignment
- Dictionary has key-value, we can change the value of a specific item by referring to its key name.
person = {'name': 'Rana', 'age': 40, 'city': 'Dhaka'}
person['city'] = "Delhi"
print("person")
Output: {'name': 'Rana', 'age': 40, 'city': 'Delhi'}
Add & remove Item Value:
- Lists are ordered, so we can use append() to add value at the end & remove() to remove any value
animals = ['cow','goat','lamb',"buffelo","camel"]
animals.append('Lion')
animals.remove('lamb')
print(animals)
Output: ['cow', 'goat', 'buffelo', 'camel', 'Lion']
- Tuples are immutable, so we can not add or remove any value.
- Sets are unordered, we can use add() to add any value & remove() to remove any value
animals = {'cow','goat','lamb',"buffelo","camel"}
animals.add('Lion')
animals.remove('lamb')
print(animals)
Output: {'camel', 'goat', 'Lion', 'buffelo', 'cow'}
- Dictionaries are mutable & have key-value, so we can add an item to the dictionary by using a new index key and assigning a value to it
person = {'name': 'Rana', 'age': 40, 'city': 'Dhaka','profession':"Data Scientist"}
person['city'] = "Delhi" # Add value
person.pop("age") #remove age
del person['profession'] #remove profession
print(person)
Output: {'name': 'Rana', 'city': 'Delhi'}
Loop through items:
List:
- We can loop through the list items by using a for-loop
animals = ['cow','goat','lamb',"buffelo","camel"]
for animal in animals:
print(animal)
Output: cow goat lamb buffelo camel
- We can print all items by referring to their index number
animals = ['cow','goat','lamb',"buffelo","camel"]
for serial in range(len(animals)):
print(animals[serial])
Output: cow goat lamb buffelo camel
- We can loop through the list items by using a while loop.
animals = ['cow','goat','lamb',"buffelo","camel"]
serial = 0
while serial < len(animals):
print(animals[serial])
serial=serial+1
Output: cow goat lamb buffelo camel
Tuple:
- We can loop through the tuple items by using a for-loop
animals = ('cow','goat','lamb',"buffelo","camel")
for animal in animals:
print(animal)
Output: cow goat lamb buffelo camel
- We can print all items by referring to their index number
animals = ('cow','goat','lamb',"buffelo","camel")
for serial in range(len(animals)):
print(animals[serial])
Output: cow goat lamb buffelo camel
- We can loop through the tuple items by using a while loop.
animals = ('cow','goat','lamb',"buffelo","camel")
serial = 0
while serial < len(animals):
print(animals[serial])
serial=serial+1
Output: cow goat lamb buffelo camel
Set:
- We can loop through the set items by using a for-loop
- But we can not loop through set items by their index number as unindexable
animals = {'cow','goat','lamb',"buffelo","camel"}
for animal in animals:
print(animal)
Output: buffelo camel goat lamb cow
animals = {'cow','goat','lamb',"buffelo","camel"}
for serial in range(len(animals)):
print(animals[serial])
Output: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-11-2e2a75af7657> in <cell line: 3>() 2 3 for serial in range(len(animals)): ----> 4 print(animals[serial]) TypeError: 'set' object is not subscriptable
animals = {'cow','goat','lamb',"buffelo","camel"}
serial = 0
while serial < len(animals):
print(animals[serial])
serial=serial+1
Output: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-12-a72ece417006> in <cell line: 5>() 4 5 while serial < len(animals): ----> 6 print(animals[serial]) 7 serial=serial+1 TypeError: 'set' object is not subscriptable
Dictionary:
- We can iterate over a dictionary using a for loop.
- By default, the loop returns the keys, but we can also use the second method below to access the values.
person = {'name': 'Rana', 'age': 40, 'city': 'Dhaka','profession':"Data Scientist"}
for info in person:
print('keys: ',info) # Get keys name only
print()
for info in person.keys():
print('keys: ',info) # Get keys name only
print()
for info in person:
print('value: ',person[info]) # Get values only
print()
for info in person.values():
print('value: ',info) # Get values only
print()
for key,value in person.items():
print(key,":",value ) # Get keys,values both
Output: keys: name keys: age keys: city keys: profession keys: name keys: age keys: city keys: profession value: Rana value: 40 value: Dhaka value: Data Scientist value: Rana value: 40 value: Dhaka value: Data Scientist name : Rana age : 40 city : Dhaka profession : Data Scientist
Join:
List:
- There are multiple methods to combine or concatenate two or more lists in Python. One of the simplest ways is by using the + operator.
- Moreover, .append() & .extend() can be used to add two list together.
cattle = ['cow','goat','lamb',"buffelo","camel"]
wild = ["tiger","lion","elephant",'bear',"dear"]
animals = cattle + wild
print(animals)
print()
for animal in cattle:
wild.append(animal)
print(wild)
print()
wild.extend(cattle)
print(wild)
Output: ['cow', 'goat', 'lamb', 'buffelo', 'camel', 'tiger', 'lion', 'elephant', 'bear', 'dear'] ['tiger', 'lion', 'elephant', 'bear', 'dear', 'cow', 'goat', 'lamb', 'buffelo', 'camel'] ['tiger', 'lion', 'elephant', 'bear', 'dear', 'cow', 'goat', 'lamb', 'buffelo', 'camel', 'cow', 'goat', 'lamb', 'buffelo', 'camel']
Tuple:
- We can join two or more tuples using the + operator.
- But we can not use .append() or .extend() as tuple is immutable.
cattle = ('cow','goat','lamb',"buffelo","camel")
wild = ("tiger","lion","elephant",'bear',"dear")
animals = cattle + wild
print(animals)
Output: ('cow', 'goat', 'lamb', 'buffelo', 'camel', 'tiger', 'lion', 'elephant', 'bear', 'dear')
Set:
Use of union():
- Returns a new set with all items from both sets.
- We can join multiple sets using commas “,”.
- We can join a set with other data types, like lists or tuples but the result will be set.
- It excludes any duplicate items.
cattle = {'cow','goat','lamb',"buffelo","camel"}
wild = {"tiger","lion","elephant",'bear',"dear"}
bird = {"sparrow", "crow", "pigeon", "eagle", "parrot"}
insect = {"ant", "bee", "butterfly", "mosquito", "spider"}
marine = ("Dolphin","Whale","Seal","Penguin")
fish = ["goldfish", "shark", "salmon", "clownfish", "guppy"]
animals_1 = cattle.union(wild) #Join two sets
print(animals_1)
print()
animals_2 = cattle.union(wild,bird,insect) #Join Multiple Sets
print(animals_2)
print()
animals_3 = cattle.union(wild,marine,fish) #Join set,tuple,list which will give only set
print(animals_3)
print()
Output: {'goat', 'camel', 'cow', 'buffelo', 'lion', 'tiger', 'dear', 'elephant', 'bear', 'lamb'} {'crow', 'eagle', 'goat', 'buffelo', 'butterfly', 'pigeon', 'mosquito', 'spider', 'bear', 'sparrow', 'parrot', 'ant', 'bee', 'camel', 'cow', 'lion', 'tiger', 'dear', 'elephant', 'lamb'} {'clownfish', 'Penguin', 'bear', 'cow', 'tiger', 'guppy', 'goat', 'Dolphin', 'Whale', 'buffelo', 'goldfish', 'camel', 'lion', 'dear', 'elephant', 'Seal', 'salmon', 'shark', 'lamb'}
Use of ” | “:
- We can use “|” instead of union() which will return a new set with all items from both sets.
- We can join multiple sets using “|”.
- We can use “|” operator only to join sets with sets, and not with other data types .
cattle = {'cow','goat','lamb',"buffelo","camel"}
wild = {"tiger","lion","elephant",'bear',"dear"}
bird = {"sparrow", "crow", "pigeon", "eagle", "parrot"}
insect = {"ant", "bee", "butterfly", "mosquito", "spider"}
marine = ("Dolphin","Whale","Seal","Penguin")
fish = ["goldfish", "shark", "salmon", "clownfish", "guppy"]
animals_1 = cattle | wild #Join two sets
print(animals_1)
print()
animals_2 = cattle | wild | bird | insect #Join Multiple Sets
print(animals_2)
print()
Output: {'goat', 'camel', 'cow', 'buffelo', 'lion', 'tiger', 'dear', 'elephant', 'bear', 'lamb'} {'crow', 'eagle', 'goat', 'buffelo', 'butterfly', 'pigeon', 'mosquito', 'spider', 'bear', 'sparrow', 'parrot', 'ant', 'bee', 'camel', 'cow', 'lion', 'tiger', 'dear', 'elephant', 'lamb'}
animals_3 = cattle | wild | marine | fish #Join set,tuple,list etc
print(animals_3)
print()
Output: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-7-b8f2a2c2ea6a> in <cell line: 1>() ----> 1 animals_3 = cattle | wild | marine | fish #Join set,tuple,list etc 2 print(animals_3) 3 print() TypeError: unsupported operand type(s) for |: 'set' and 'tuple'
Use of update():
- Inserts all items from one set into another.
- update() changes the original set and does not return a new set like union().
- We can update multiple sets using commas “,”.
- It excludes any duplicate items.
my_fish = {"Guppy","Mollie","Goldfish"}
gifted_fish = {"Neon Tetra","Angelfish", "Mollie", "Zebra Danio", "Corydoras Catfish"}
purchased_fish = {"Oscar", "Discus", "Plecostomus", "Platy","Tiger Barb", "Cherry Barb"}
my_fish.update(gifted_fish) #Update my fish collection with my gift fishes, mollie was duplicate , so took one 'mollie'
print(my_fish)
Output: {'Angelfish', 'Corydoras Catfish', 'Zebra Danio', 'Guppy', 'Mollie', 'Neon Tetra', 'Goldfish'}
my_fish.update(gifted_fish,purchased_fish) #use ", " to add more than one set
print(my_fish)
Output: {'Angelfish', 'Oscar', 'Corydoras Catfish', 'Zebra Danio', 'Plecostomus', 'Discus', 'Guppy', 'Tiger Barb', 'Mollie', 'Neon Tetra', 'Platy', 'Goldfish', 'Cherry Barb'}
Use of intersection():
- We can use intersection() or “&” operator to keep ONLY the duplicates.
- The “&” operator only allows to join sets with sets, and not with other data types like we can do with the intersection() method.
- The intersection_update() method will also keep ONLY the duplicates, but it will change the original set instead of returning a new set.
my_pet = {"Dog", "Cat", "Rabbit", "Hamster", "Guinea Pig"}
gifted_pet = { "Lizard", "Snake", "Turtle","Cat", "Rabbit"}
purchased_fish = {"Sugar Glider", "Degu", "Prairie Dog", "Frog", "Snake"}
pet_common = my_pet.intersection(gifted_pet) #created new set
print(pet_common)
print()
pet_common = my_pet & gifted_pet #created new set
print(pet_common)
print()
my_pet.intersection_update(gifted_pet) # Changed my_pet set items
print(my_pet)
Output: {'Cat', 'Rabbit'} {'Cat', 'Rabbit'} {'Cat', 'Rabbit'}
Use of difference():
- Return a new set that will contain only the items from the first set that are not present in the other set.
- We can use ” – ” instead of difference().
- The “-“ operator only allows to join sets with sets, and not with other data types like difference() method does.
my_pet = {"Dog", "Cat", "Rabbit", "Hamster", "Guinea Pig"}
gifted_pet = { "Lizard", "Snake", "Turtle","Cat", "Rabbit"}
purchased_fish = {"Sugar Glider", "Degu", "Prairie Dog", "Frog", "Snake"}
pet_common = my_pet.difference(gifted_pet) #Created new set
print(pet_common)
print()
pet_common = my_pet - gifted_pet #created new set
print(pet_common)
print()
my_pet.difference_update(gifted_pet) # Changed my_pet set items
print(my_pet)
Output: {'Guinea Pig', 'Dog', 'Hamster'} {'Guinea Pig', 'Dog', 'Hamster'} {'Hamster', 'Guinea Pig', 'Dog'}
Use of symmetric_difference():
- Return the elements that are NOT present in both sets.
- We can use “ ^ ” or symmetric_difference().
- The ^ operator only allows to joining sets with sets, and not with other data types like the symmetric_difference() method does.
- The symmetric_difference_update() method will also keep all but the duplicates, but it will change the original set instead of returning a new set.
my_pet = {"Dog", "Cat", "Rabbit", "Hamster", "Guinea Pig"}
gifted_pet = { "Lizard", "Snake", "Turtle","Cat", "Rabbit"}
purchased_fish = {"Sugar Glider", "Degu", "Prairie Dog", "Frog", "Snake"}
pet_common = my_pet.symmetric_difference(gifted_pet) #created new set
print(pet_common)
print()
pet_common = my_pet ^ gifted_pet #created new set
print(pet_common)
print()
my_pet.symmetric_difference_update(gifted_pet) # Changed my_pet set items
print(my_pet)
Output: {'Lizard', 'Hamster', 'Guinea Pig', 'Snake', 'Dog', 'Turtle'} {'Lizard', 'Hamster', 'Guinea Pig', 'Snake', 'Dog', 'Turtle'} {'Lizard', 'Hamster', 'Guinea Pig', 'Snake', 'Dog', 'Turtle'}
Sort:
List:
- We can use sort() function to sort the list alphanumerically.
- It is ascending by default.
- To sort descending, we can use the keyword argument reverse = True.
- The sort() method tries to compare elements to arrange them in order, but it can’t compare an integer with a string, leading to the TypeError.
- sort() method is case sensitive, resulting in all capital letters being sorted before lowercase letters.
- We can use reverse() method to reverse the current sorting order of the elements without considering alphanumerically sorting.
cattle = ['cow','goat','lamb',"buffelo","camel"]
cattle_weight = [140,30,40,140,180]
cattle.sort() #Sort string ascending
print(cattle)
print()
cattle_weight.sort() #Sort integer ascending
print(cattle_weight)
print()
cattle.sort(reverse=True) #Sort string descending
print(cattle)
print()
cattle_weight.sort(reverse=True) #Sort integer descending
print(cattle_weight)
print()
wild = ["tiger","lion","Elephant","bear","Dear","elephant","Leo"]
wild.sort() #Sort string ascending
print(wild)
print()
wild.sort(reverse=True) #Sort string descending
print(wild)
print()
bird = ["sparrow", "crow", "pigeon", "eagle", "parrot"]
bird.reverse() #Reverse the order only
print(bird)
print()
Output: ['buffelo', 'camel', 'cow', 'goat', 'lamb'] [30, 40, 140, 140, 180] ['lamb', 'goat', 'cow', 'camel', 'buffelo'] [180, 140, 140, 40, 30] ['Dear', 'Elephant', 'Leo', 'bear', 'elephant', 'lion', 'tiger'] ['tiger', 'lion', 'elephant', 'bear', 'Leo', 'Elephant', 'Dear'] ['parrot', 'eagle', 'pigeon', 'crow', 'sparrow']
Tuple:
- Tuples are immutable, so we can’t use sort() directly on them.
- However, we can use sorted() which will sort the elements and return a new sorted list.
cattle = ('cow','goat','lamb',"buffelo","camel")
sorted_cattle = sorted(cattle) # new list i/o tuple will be in output
print(cattle) # No change will be in original tuple
print()
print(sorted_cattle)
Output: ('cow', 'goat', 'lamb', 'buffelo', 'camel') ['buffelo', 'camel', 'cow', 'goat', 'lamb']
Set:
- Sets are unordered collections, so they do not support sorting.
- However, we can use sorted() which will sort the elements and return a new sorted list.
cattle = {'cow','goat','lamb',"buffelo","camel"}
sorted_cattle = sorted(cattle) # new list i/o tuple will be in output
print(cattle) # No particular sorting happened in original set
print()
print(sorted_cattle)
Output: {'buffelo', 'cow', 'lamb', 'goat', 'camel'} ['buffelo', 'camel', 'cow', 'goat', 'lamb']
Membership:
- Refers to checking whether a specific element exists within a list, tuple, set & key in dictionary in Python.
- This is typically done using the in and not in operators.
print("---------------List Membership---------------------------")
my_animals_l = ['cow','goat','lamb',"buffelo","camel"]
if 'goat' in my_animals_l:
print('I have one goat') # "goat" exists in my_animals list
print()
if 'dog' not in my_animals_l: # "dog" not exists in my_animals list
print('I will buy one dog')
print("---------------Tuple Membership---------------------------")
my_animals_T = ('cow','goat','lamb',"buffelo","camel")
if 'goat' in my_animals_T:
print('I have one goat') # "goat" exists in my_animals tuple
print()
if 'dog' not in my_animals_T: # "dog" not exists in my_animals tuple
print('I will buy one dog')
print("---------------Set Membership---------------------------")
my_animals_S = {'cow','goat','lamb',"buffelo","camel"}
if 'goat' in my_animals_S:
print('I have one goat') # "goat" exists in my_animals set
print()
if 'dog' not in my_animals_S: # "dog" not exists in my_animals set
print('I will buy one dog')
print("---------------Dictionary Membership---------------------------")
my_animals_D = {'cow':"first",'goat':"second",'lamb':"third"}
if 'goat' in my_animals_D:
print('goat is key of my dictionary') # "goat" exists in my_animals dictionary
print()
if 'dog' not in my_animals_D: # "dog" not exists in my_animals dictionary
print('dog is not key of my dictionary')
print()
if 'second' in my_animals_D.values():
print('second is value of my dictionary') # "second" exists in my_animals dictionary
print()
if 'fourth' not in my_animals_D.values(): # "fourth" not exists in my_animals dictionary
print('fourth is not value of my dictionary')
Output: ---------------List Membership--------------------------- I have one goat I will buy one dog ---------------Tuple Membership--------------------------- I have one goat I will buy one dog ---------------Set Membership--------------------------- I have one goat I will buy one dog ---------------Dictionary Membership--------------------------- goat is key of my dictionary dog is not key of my dictionary second is value of my dictionary fourth is not value of my dictionary
Indexing:
List:
- Indexing allows access to individual elements in a list using their position (index).
- Positive indexing starts from 0 for the first element.
- Negative indexing starts from -1 for the last element
Tuple:
- Just like lists, tuples use zero-based indexing.
- Positive indexing starts from 0 for the first element.
- Negative indexing starts from -1 for the last element
Set:
- Sets are unordered, so there is no concept of an “index” for elements. We can’t retrieve an element by its position in the set.
Dictionary:
- Dictionary indexing is different from list or tuple indexing.
- In a dictionary, we access elements using keys rather than numeric indices.
- Each key is associated with a value, and we can use the key to retrieve the corresponding value.
- The get() method is another way to retrieve a value by its key.
print("---------------------List Indexing----------------")
fruits = ['apple', 'banana', 'cherry', 'date',"mango"]
# Accessing elements using positive indexing
first_fruit = fruits[0]
print("first_fruit :",first_fruit)
second_fruit = fruits[1]
print("second_fruit :",second_fruit)
# Accessing elements using negative indexing
last_fruit = fruits[-1]
print("last_fruit :",last_fruit)
second_last_fruit = fruits[-2]
print("second_last_fruit :",second_last_fruit)
print("---------------------Tuple Indexing----------------")
fruits = ('apple', 'banana', 'cherry', 'date',"mango")
# Accessing elements using positive indexing
first_fruit = fruits[0]
print("first_fruit :",first_fruit)
second_fruit = fruits[1]
print("second_fruit :",second_fruit)
# Accessing elements using negative indexing
last_fruit = fruits[-1]
print("last_fruit :",last_fruit)
second_last_fruit = fruits[-2]
print("second_last_fruit :",second_last_fruit)
print("---------------------Dictionary Indexing----------------")
my_animals = {'cow':"first",'goat':"second",'lamb':"third"}
cow_sl=my_animals["cow"]
print("cow_sl",cow_sl)
cow_sl=my_animals.get("cow")
print("cow_sl",cow_sl)
Output: ---------------------List Indexing---------------- first_fruit : apple second_fruit : banana last_fruit : mango second_last_fruit : date ---------------------Tuple Indexing---------------- first_fruit : apple second_fruit : banana last_fruit : mango second_last_fruit : date ---------------------Dictionary Indexing---------------- cow_sl first cow_sl first
Nested Indexing:
- Refers to accessing elements within nested data structures like lists, tuples, sets, and dictionaries that contain other collections as their elements.
- Lists and tuples support nested indexing directly using
[index][subindex]
. - Sets are unordered and do not support indexing directly.
- Dictionaries allow nested access using
['key']['subkey']
if the values are dictionaries themselves.
print("-------------------Nested list indexing-----------------------")
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Accessing the first element of the second list
element = my_list[1][0]
print(element)
# Accessing the third element of the third list
element = my_list[2][2]
print(element)
print("-------------------Nested tuple indexing-----------------------")
my_tuple = ((10, 20, 30), (40, 50, 60), (70, 80, 90))
# Accessing the second element of the first tuple
element = my_tuple[0][1]
print(element)
# Accessing the first element of the third tuple
element = my_tuple[2][0]
print(element)
print("-------------------Nested dictionary indexing-----------------------")
my_dict = {'a': {'x': 1, 'y': 2}, 'b': {'x': 3, 'y': 4}}
# Accessing the value associated with key 'x' in the nested dictionary under key 'a'
element = my_dict['a']['x']
print(element)
# Accessing the value associated with key 'y' in the nested dictionary under key 'b'
element = my_dict['b']['y']
print(element)
Output: -------------------Nested list indexing----------------------- 4 9 -------------------Nested tuple indexing----------------------- 20 70 -------------------Nested dictionary indexing----------------------- 1 4
Slicing:
List:
- Slicing allows to extract a subset of the list by specifying a range of indices.
- The syntax for slicing is list[start:stop:step].
- start: The index where the slice starts (inclusive).
- stop: The index where the slice ends (exclusive).
- step: The step size or increment between indices (optional).
Tuple:
- Slicing a tuple works similarly to slicing a list.
- Tuple slicing allows to extract a portion or subset of a tuple by specifying a range of indices.
- The syntax for slicing a tuple is tuple[start:stop:step].
- start: The index where the slice begins (inclusive).
- stop: The index where the slice ends (exclusive).
- step: The step size or interval between indices (optional)
- If we omit the start index, the slice will start from the beginning of the tuple.
- If we omit the stop index, the slice will continue to the end of the tuple.
- We can use only step specifies the interval between elements in the slice.
- By using a negative step, we can reverse the tuple.
Set:
- We cannot perform slicing operations on a set because it is unordered.
Dictionary:
- We cannot directly slice a dictionary because it is not an ordered collection of elements.
print("---------------------------------------List Slicing---------------------")
fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry',"blueberry","mango"]
# Slicing from index 1 to 3
fruits_1_to_3 = fruits[1:4]
print("fruits_1_to_3:",fruits_1_to_3)
# Slicing from index 1 to 7
fruits_1_to_6 = fruits[1:7:2]
print("fruits_1_to_6:",fruits_1_to_6)
# Slicing from the beginning to index 2
fruits_from_start = fruits[:3]
print("fruits_from_start:",fruits_from_start)
# Slicing from index 2 to the end
fruits_to_end = fruits[2:]
print("fruits_to_end:",fruits_to_end)
# Slicing with a step of 2
every_second_fruit = fruits[::2]
print("every_second_fruit:",every_second_fruit)
# Reverse the list
reverse_fruits = fruits[::-1]
print("reverse_fruits:",reverse_fruits)
# Reverse the list with a step of 2
reverse_fruits_2 = fruits[::-2]
print("reverse_fruits_2:",reverse_fruits_2)
print("---------------------------------------Tuple Slicing---------------------")
fruits = ('apple', 'banana', 'cherry', 'date', 'elderberry',"blueberry","mango")
# Slicing from index 1 to 3
fruits_1_to_3 = fruits[1:4]
print("fruits_1_to_3:",fruits_1_to_3)
# Slicing from index 1 to 7
fruits_1_to_6 = fruits[1:7:2]
print("fruits_1_to_6:",fruits_1_to_6)
# Slicing from the beginning to index 2
fruits_from_start = fruits[:3]
print("fruits_from_start:",fruits_from_start)
# Slicing from index 2 to the end
fruits_to_end = fruits[2:]
print("fruits_to_end:",fruits_to_end)
# Slicing with a step of 2
every_second_fruit = fruits[::2]
print("every_second_fruit:",every_second_fruit)
# Reverse the tuple
reverse_fruits = fruits[::-1]
print("reverse_fruits:",reverse_fruits)
# Reverse the tuple with a step of 2
reverse_fruits_2 = fruits[::-2]
print("reverse_fruits_2:",reverse_fruits_2)
Output: ---------------------------------------List Slicing--------------------- fruits_1_to_3: ['banana', 'cherry', 'date'] fruits_1_to_6: ['banana', 'date', 'blueberry'] fruits_from_start: ['apple', 'banana', 'cherry'] fruits_to_end: ['cherry', 'date', 'elderberry', 'blueberry', 'mango'] every_second_fruit: ['apple', 'cherry', 'elderberry', 'mango'] reverse_fruits: ['mango', 'blueberry', 'elderberry', 'date', 'cherry', 'banana', 'apple'] reverse_fruits_2: ['mango', 'elderberry', 'cherry', 'apple'] ---------------------------------------Tuple Slicing--------------------- fruits_1_to_3: ('banana', 'cherry', 'date') fruits_1_to_6: ('banana', 'date', 'blueberry') fruits_from_start: ('apple', 'banana', 'cherry') fruits_to_end: ('cherry', 'date', 'elderberry', 'blueberry', 'mango') every_second_fruit: ('apple', 'cherry', 'elderberry', 'mango') reverse_fruits: ('mango', 'blueberry', 'elderberry', 'date', 'cherry', 'banana', 'apple') reverse_fruits_2: ('mango', 'elderberry', 'cherry', 'apple')
Count:
- To count occurrences of elements in a list or tuple, we can use count() function.
- To count occurrences of all unique elements in a list or tuple, we can use the collections.Counter class.
- Concept of “counting” occurrences of elements does not directly apply to sets as set does not store duplicate entries.
- Dictionary also has unique key but values can be duplicated , so we can use the collections.Counter class.
print("-----------------count list------------------------------")
fruits = ['apple', 'banana', 'cherry', 'apple', 'banana', 'apple']
# Count occurrences of 'apple'
apple_count = fruits.count('apple')
print("apple_count",apple_count)
from collections import Counter
# Count all elements
element_counts = Counter(fruits)
print("element_counts",element_counts)
print("-----------------count tuple------------------------------")
fruits = ('apple', 'banana', 'cherry', 'apple', 'banana', 'apple')
# Count occurrences of 'apple'
apple_count = fruits.count('apple')
print("apple_count",apple_count)
from collections import Counter
# Count all elements
element_counts = Counter(fruits)
print("element_counts",element_counts)
print("-----------------count dictionary------------------------------")
from collections import Counter
my_dict = {'apple': 4, 'banana': 6, 'cherry': 2, 'mango': 4, 'kiwi': 2}
# Count occurrences of each value
value_counts = Counter(my_dict.values())
print(value_counts)
Output: -----------------count list------------------------------ apple_count 3 element_counts Counter({'apple': 3, 'banana': 2, 'cherry': 1}) -----------------count tuple------------------------------ apple_count 3 element_counts Counter({'apple': 3, 'banana': 2, 'cherry': 1}) -----------------count dictionary------------------------------ Counter({4: 2, 2: 2, 6: 1})
Index position:
- Lists & tuples are ordered, so we can use the index() method to find the index of an element.
- Sets are unordered and do not support indexing directly.
- Dictionaries do not have indexes
- Remember that trying to find the index of an element not present in the collection will result in a ValueError.
print("------------------Index Position list------------------")
fruits = ['apple', 'banana', 'cherry', 'date']
# Get the index position of 'banana'
index_position = fruits.index('banana')
print(index_position)
print("------------------Index Position tuple------------------")
fruits = ('apple', 'banana', 'cherry', 'date')
# Get the index position of 'cherry'
index_position = fruits.index('cherry')
print(index_position)
Output: ------------------Index Position list------------------ 1 ------------------Index Position tuple------------------ 2