16: Collections
Collections
Collections are also variables, but these variables can hold multiple values while a simple variable can store only one value.
- We know that variables can hold the data.
- But a variable can only hold a single item of data.
- In the real world, it is required to use many data items like hundreds, thousands even millions of data items in a program.
- If we create a normal variable for each data item then it is not possible for programmers due to typing efforts and also there are technical reasons.
- Collections help a programmer to create hundreds, thousands or even millions of variables using a single statement.
- All collections can be discussed under the following properties.
- Indexing: Some collection types are indexable and some are not.
- Mutability: Elements in some collections mutable and in some are not mutable.
- Nest able Collections: A collection can or cannot store any other collection inside it.
- There are four types of collections available in Python.
Lists
- Lists are simple collections that can hold many items.
- Each item in the list is called an element.
my_list = [2, 3, 4, 12, 3]
Code 1: A Simple List with 5 Integer Elements
- List is like a simple variable but we assign my_list to five elements which are integers.
- The list of elements must be defined between pairs of brackets [].
- The elements must be comma separated.
- List can easily output by print statement like simple variable
- Every element has an address inside the list that is called index number.
- Index numbers start from 0. It means the first item of the list is situated on zero location.
- In the above example, 2 is at 0, 3 at 1, 4 at 2, 12 at 4 and 3 at 4 index numbers.
- We can access individual elements by their index number.
num = my_list[2]
Code 2: Accessing Individual Element of the List
- It will assign 4 in num because there 4 stored on index number 2.
- The list is dynamic in size. Developers can add or remove elements during program execution.
- Following are important methods used to work with lists.
- append
- insert
- remove
- clear
- The append method adds a new element at the end of the list.
my_list.append (10)
Code 3: Using append Method
- After execution of code 3, our list looks like [2, 3, 4, 12, 3, 10].
- 10 added at the end.
- The insert method adds a new element at a given location. The next element drifts to the right.
my_list.insert (0, 55)
Code 4: Inserting new Element at given Location
- 0 is the location, which means the first location of the list and 55 is the value that we want to insert.
- Now our list looks like [55, 2, 3, 4, 12, 3, 10]. Consider that code 3 also the part.
- 55 is added 0 location and 2 (which was previously at first) now moves to location 1 and all other elements move one step right.
- The remove method used to delete given element.
my_list.remove (4)
Code 5: Removing 4 from List
- We know that 4 is at location 3. This method will delete this element and all elements after it will shift to one step left. The new list looks like [55, 2, 3, 12, 3, 10]. Now 12 is moved to location 3.
- The clear method removes all elements from the list.
- As list size is dynamic and can be changed due operations on list, we have to find the list size often. The len method uses find the size or count the number of elements in the list.
size = len (my_list)
Code 6: Get the Size of List
- If the last version of the list is after code 5 then the size variable will contain 6 because we have six elements in the list.
- We can slice the list by using “:” (colon symbol) in the list. It provides the use of part of a list.
- General structure like this [start : stop : step].
- Start: starting index (included)
- Stop: ending index (exclude d)
- Step: items to skip
- Consider the following example
my_list = [2, 3, 4, 12, 3, 15, 6, 7, 19, 9, 0, 18, 21]sub_list = my_list[2:10:3]print(sub_list)
- We have set the slicing [2:8:3].
- 2 is the starting which will include means value at location 2 (value 4) will be included.
- 10 is the ending index which will not include the mean value at location 10 ( value 0) will not be the part of sub_list.
- 3 is the step that means after choosing the starting index, it will choose the next 3rd element.
- According to this example, first it will choose 4 because it is starting, next it will skip 2 elements (12 and 3) and choose 3rd which is 15 then again skip 2 elements next to it (6 and 7) and choose 19 next it will again skip two elements (9 and 0) but 0 is also at ending index so selection of more items will end and sub_list will have [4, 15, 19].
- All three parameters of slicing are optional and can be omitted.
- sub_list = my_list[8:] will have [19, 9, 0, 18, 21]. All elements after location number 8 (location 8 included).
- sub_list = my_list[:4] will have [2, 3, 4, 12]. First 4 elements. Location 4 not included.
- sub_list = my_list[::4] will have [2, 3, 19, 21]. Get all elements but skip 3 elements between and select 4th.
- More corollaries can be defined.
for Loop
- The for loop is specifically defined for lists.
- In for loop there is no index element that increases or decreases or checks the False for loop termination.
- We have a loop variable that automatically picks up the element from the list and stores it into a variable and we can perform operations on this variable.
- For example, we want to calculate the square of each element in a list.
my_list = [2, 3, 4, 12, 3, 15, 6, 7, 19, 9, 0, 18, 21]for x in my_list:Â Â print (x ** 2)
Code 8: Using for Loop in List
- We have a list of some elements.
- In for loop, use a variable x that take element from my_list
- On the first iteration, it will take the first element from list, 2 and put it into variable x.
- Next, we go into the loop body and print the square 2, 4.
- for loop will automatically pick up next item 3 and go in to loop body print the 9.
- We can see that there NO True/False statement producer in for construct.
- The loop will automatically terminate when the last element is picked.
- In fact, x makes a copy of the value from the list element. When we perform some operation on loop variable x.
- You can change your variable name according to your choice.
- For list operations, for loop is considered much better than while.
- A list can also store multiple data types like this.
product = [1, "Bread", 2.5]
Code 9: List with different Data Type Values
- We can see that there are three different data types used in a single list. First is product id which is integer, second is product name which is string and third is the float value, price.
- This is not a different kind of list so all operations like append, insert, remove, clear and slicing can be performed similarly on this.
- We can also use a list inside a list.
products = [  [1, "Bread", 2.5],  [2, "Milk", 1.5],  [3, "Eggs", 3.0],  [4, "Butter", 4.0],  [5, "Cheese", 5.0]]
Code 10: List Inside List
- We have created a list of products and data of each product also put in the form of an inner-list inside products.
- If we want to get a product from this list in a separate list then code would be like this.
bread = products[0]milk = products[1]cheese = products[4]
Code 11: Accessing a List item by Index
- The bread, milk and cheese are all lists that contain data of their respective items.
- We can use a for loop to traverse the data of this kind of lists.
products = [  [1, "Bread", 2.5],  [2, "Milk", 1.5],  [3, "Eggs", 3.0],  [4, "Butter", 4.0],  [5, "Cheese", 5.0]]for product in products:  print (f"ID: {product[0]}, Name: {product[1]}, Price: ${product[2]}")
Code 12: Traversing Inner List by for Loop
- Loop variable product will take each element from products list.
- product itself a list variable so we have to print the values by providing indexes of given information.
- Output of the code 12 will be like this.
Figure 1: Output of Code 12
Sets
- Sets are similar to lists but contain unique values.
- For example, if a set contains values 1, 2, 3, 4 and we try to put 4 again into the set then no operation will be performed because 4 is already in it.
- Set supports all other types of data and even mixed items with different data types like list.
- We can create a set with this code.
set1 = {1, 2, 3, 4, "ff"}
Code 13: Creating a Set
- We can also convert a list into set.
set1 = set ([1, 2, 3, 4, "ff"])
Code 14: Converting a List into Set by set Function
- We can add new items using the add method.
- We can remove items by discard method.
- To delete all items from the set, we use clear.
- We can also use for to manipulate the items in the set.
- A set can be added to a list but a list cannot be added to a set.
- The most powerful aspect of sets is that sets can perform set operations. Normally, the concepts of set theory have been taught in high school level mathematics.
- Union
- Intersection
- Difference
- Symmetric Difference
- Union means all elements of both sets. If some elements are common then these will present only once.
set1 = {1, 2, 3}set2 = {3, 4, 5}set3 = set1 | set2
Code 15: Union of Sets
- set1 will union with set2 and the result will save to set3.
- After union, the set3 will contain {1, 2, 3, 4, 5}
- 3 is common in both sets but it will occur only once in set3.
- Intersection will only have common elements of both sets.
set3 = set1 & set2
Code 16: Intersection of Sets
- set3 will have {3}.
- Union and intersection have commutative law.
- The difference means all the values of the first set which are not in the second.
set3 = set1 - set2
Code 17: Difference of Sets
- set3 will contain {1, 2}
- Symmetric Difference means all members of both sets which are not common.
set3 = set1 ^ set2
Code 18: Symmetric Difference of Sets
- The result will be {1, 2, 4, 5}.
- We can see that 3 is missing because it is the common value in both sets.
- We can convert to set into a list and a list into a set.
- Indexing is not supported in sets.
Tuple
- Tuples are immutable collections. You cannot change, add or delete the values in a tuple after they are created.
- Tuples use parenthesis () to hold the data.
- Tuples are similar with lists in many ways.
- They are indexed. We can access any element with the help of an index number.
- We can use for loop to get values.
- Tuple supports all data types and mixed data elements.
- A tuple can contain another tuple inside it
- A tuple can contain a list inside it.
- It can hold similar values multiple times.
- Tuples can initialize with fixed values or can be defined with the help of a list.
tuple1 = (1, 2, 3)my_list = [1, 2, 3, 4]tuple2 = tuple(my_list)x = 10y = 20tuple3 = (x, y, ["aa", "bb"])
Code 19: Creating Tuple with different techniques
- tuple1 initialized with fixed value.
- tuple2 initializes with the help of list.
- tuple3 is created with the help of variables.
- As a tuple is immutable, we can use tuples where we want to prevent the values from changing or removing.
- Tuples are faster in processing than other collections.
Dictionaries
- Dictionaries are key-value pair like collection
- These are very similar to JSON data.
my_dict = {  "name": "Ali",  "age": 25,  "city": "Bahawalpur"}
Code 20: A Simple Dictionary
- Dictionaries have following properties
- These are mutable. We can change data in dictionaries like lists and sets.
- These are not indexed. We cannot use an index number to access any element.
- We can use any data type in the key part except list, set and dictionary.
- We can use any data type in value.
- The colon symbol (:) is used to define key and value pairs.
- On left side of colon is called key while on right side called value
- For example, in code 19, “name” is the key and “Ali” is the value.
- As dictionaries are not indexed so we have to use keys to access the element.
print (my_dict["name"])
Code 21: Accessing Element of Dictionary by Key
- It will print “Ali” because the name key contains this value.
- Similarly, we can change the value of a key.
my_dict["name"] = "Suleman"
Code 22: Changing Value of an Item in Dictionary
- If a key does not already exist in the dictionary but we can still add it with a simple assignment.
my_dict["email"] = "suleman@gmail.com"
Code 23: Add a New Key in Dictionary
- We can see that when we initialized our dictionary, we did not have an “email” key.
- But without using any add or insert method, we add a new key in the dictionary.
- Two methods can be used to remove items from a dictionary.
del my_dict["city"]my_dict.pop("email")
Code 24: Removing Values from Dictionary
- Using the del keyword before the dictionary name will remove the item associated with the given key.
- Similarly, pop method will also delete the key-value on the base of the provided key.
- If we use the pop method without parameters then it will remove the last item from the dictionary.
- We can use the keys () and values () methods to get all keys and values.
- The items () method provides the list of all key-value pairs.
- We can access the dictionary items by using for loop.
for k in my_dict:Â Â print (f"{k}: {my_dict[k]}")
Code 25: Using for Loop to Traverse Dictionary
- k is the loop variable and it will only pick the keys from the dictionary.
- During the execution of the loop, we can use this key to get the value of it as we use it inside print.
- We can also use the items method in for loop for the same purpose.
for k in my_dict.items():Â Â print (f"{k}: {my_dict[k]}")
Code 26: Using Item Method in for Loop








