section 6 notes
section 6 notes
• print(people)
To print an individual element inside a list, every item in the list has an index position.
The first element has an index position of 0.
• print(people[0])
• print(people[1])
• print(numbers[0])
In the next lecture, we will perform some operations on the list.
Lists are ordered, which means that a list is not just a collection of items; the items are
in a specific order, and their order does matter.
For example, the two lists:
• a = [1, 2]
• b = [2, 1]
are not the same.
• print(a == b)
You will get the result as false.
List slicing:
List slicing is a way to extract a portion of a list in Python.
• a[m:n]
Returns a sublist of a starting from index m up to but not including index n.
In the following example, we have a list of fruits and we are slicing the list to extract
certain portions:
• # -ve index -6 -5 -4 -3 -2
-1
• fruits = ['apple', 'mango', 'peach', 'orange', 'watermelon',
'grape']
• # index 0 1 2 3 4 5
•
• # list slicing
• print(fruits[0:3]) # prints ['apple', 'mango', 'peach']
• print(fruits[1:3]) # prints ['mango', 'peach']
Here, the first slice fruits[0:3] returns a sublist of fruits starting from index 0 up to
but not including index 3. So it includes the elements at indices 0, 1, and 2 which are
'apple', 'mango', and 'peach' respectively.
Similarly, the second slice fruits[1:3] returns a sublist starting from index 1 up to
but not including index 3. So it includes the elements at indices 1 and 2 which are
'mango' and 'peach' respectively.
List slicing using negative indexing:
List functions:
• print(len(fruits))
• fruits.insert(index,"Element to be inserted")
• fruits.insert(1,"Pineapple")
• fruits.append('Hello')
• fruits.extend(['guava', 'apricot'])
Now the fruits will be added as individual items.
• fruits.remove('apple')
• fruits.pop()
• print(fruits)
Finding the index of an item in a list:
• print(fruits.index('apple'))
Tuples:
Like lists, tuples are also collections of items or objects.
However, the difference between tuples and lists is that tuples are immutable.
Once the items in the tuple are defined, we cannot change them.
• # Creating a tuple
• fruits = ('apple', 'orange', 'mango', 'pineapple')
• # Printing a tuple
• print(fruits)
• # Immutability of a tuple
• fruits[1] = 'peach'
• print(fruits)
• # Indexing
• print(fruits[1])
• # Slicing
• print(fruits[1:3])
• # Negative indexing
• print(fruits[-1])
Advantages of using a tuple:
Program execution is fast with tuples. As tuples are immutable, they should be used
when we don't want the data to be changed.
Dictionaries:
Dictionaries are mutable, and we can change the value of a certain key. Let's try
changing the age.
• people["Rob"] = 90
• print(people["Rob"])
We can have anything as a key-value pair in a dictionary. For example, we can have an
integer as a key and a string as a value, which is exactly opposite to what we have
currently. However, we cannot have the same key-value in a single dictionary.
Another way to create a dictionary is by using the dict() function. The argument to the
dict() function should be a key-value pair.
• # We pass values as keyword arguments to the dict function.
• # We have not learned about keyword arguments, but we will
discuss them when we learn about functions.
• people = dict(
• john=32,
• rob=45,
• tim=20
• )
• print(people["john"])
• del people["John"]
• print(people)
Sets:
A mathematical set is nothing but a collection of unique elements.
Similarly, a set in Python is a collection of elements where each element is unique and
duplicates are not allowed.
When creating a set, if duplicates are present, the set will automatically remove them:
• numbers = {1,2,3,4,1,4}
• print(numbers) # Output: {1, 2, 3, 4}
• names = {'John','Rob','Mike','John'}
• print(names) # Output: {'Rob', 'John', 'Mike'}
To create an empty set, we cannot use empty curly braces ({}) as it creates an empty
dictionary. We need to use the set() function:
• s = set()
A set can contain elements of different data types:
• s = {"John",2,4.5,True}
• print(s) # Output: {2, 4.5, True, 'John'}
Note that the order of elements is not retained in a set.
Set operations:
Union:
When you perform the union of two sets, you get all the elements of set a and all the
elements of set b, but with no duplicate entries.
• seta = {1, 2, 3, 4, 5}
• setb = {4, 5, 6, 7, 8}
•
• # union
• print(seta | setb)
• # the above could also be written as
• print(seta.union(setb))
Intersection:
The intersection of two sets includes only those values which are common between the
two sets.
• seta = {1, 2, 3, 4, 5}
• setb = {4, 5, 6, 7, 8}
•
• # intersection
• print(seta & setb)
• # the above code could also be written as
• print(seta.intersection(setb))
Difference operation:
The difference operation takes the elements of set a and removes all the elements
which are present in set b.
It removes the values from set a which are common to both set a and set b.
• # difference
• print(seta - setb)
• # the above code could also be written as
• print(seta.difference(setb))
Symmetric difference:
The symmetric difference returns only those elements that are either in set a or in set b
but not both.
• print(seta ^ setb)
• # this could also be written as
• print(seta.symmetric_difference(setb))
• seta.add(10)
• print(seta)
Removing elements from a set:
• seta.remove(1)
• print(seta)
• seta.discard(10)
• print(seta)
Pop:
This removes and returns a randomly chosen element from a set.
• a = seta.pop()
• print(a)
Clear:
This removes all the elements from a set.
• seta.clear()
• print(seta)
• products = {
• 'phone': 100,
• 'tablet': 200,
• 'computer': 300,
• 'laptop': 400,
• 'journal': 40
• }
•
• # Print all the items inside the dictionary
• print(products)
•
• # Search for the price of a product
• product = input("Enter the product to get the price: ")
• print(f"The price of {product} is ${products[product]}")
•
• # Add a product along with its price
• new_product = input("Enter the product you want to add: ")
• new_product_price = input(f"Enter the price for {new_product}: ")
• products[new_product] = new_product_price
•
• # Show the entire dictionary
• print(f"Product successfully added. Here is the list of products:
{products}")
•
• # Delete a product
• deleted_product = input("Enter the product you want to delete: ")
• del products[deleted_product]
• print(f"Product successfully deleted. Here is the list of
products: {products}")
•
• # Change the price of a product
• price_change_product = input("Enter the product to change the
price: ")
• price_change = input(f"Enter the new price for
{price_change_product}: ")
• products[price_change_product] = price_change
• print(f"Price successfully changed. Here is the list of p