Hello everyone, I hope you are doing well. So today we will learn about collection data types in python.
So far we have seen built-in types like int, float, bool, str int, float, and bool are considered to be simple or primitive data types.
You may also like this: How to setup Eclipse IDE for Python?
Let’s start with python collection data types.
Wait, why we need collection data types.
when we want to treat some data as a group, it would not be good to create individual variables for each data. We can store them together as a collection
You may also like these:
Python List datatypes
The list is an ordered sequence of items. It is one of the most used data types in Python and is very flexible.
a = [1, 2.2, ‘python’]
Items in python need not be of the same type.
Suppose we want to store the ticket numbers allocated to each passenger traveling on a flight. Instead of using a separate variable for each ticket number, we can use a list as shown below.
Lists are mutable, meaning, the value of elements of a list can be altered.
In case of having different variables for each ticket number, variables will be stored in separate memory locations. Whereas in the case of a list, the elements will be stored in contiguous memory locations.
You may also like this: Python operators and variables – Day 3
Each element in the list has a position known as index starting from 0.
We can directly access any item of list by writing it’s index.
Syntax for accessing item: List_name[index]
Example: number = List_name[3]
We can directly modify list item
Syntax: List_name[index] = value
Example: List_name[3] = 10988
If we have a list of 10 items then we cannot write
List_name[11] It will result in Out of bound exception.
If we write List_name[10] it will also result in Out of bound exception because the index starts with 0.
Creating a list:
Creating an empty list | sample_list=[] | |
Creating a list with known size and known elements | sample_list1=[“Mark”,5,”Jack”,9, “Chan”,5] sample_list2=[“Mark”,”Jack”, “Chan”] | List can store both homogeneous and heterogeneous elements |
Creating a list with known size and unknown elements | sample_list=[None]*5 | None denotes an unknown value in Python |
Length of the list | len(sample_list) | Displays the number of elements in the list |
Random access of elements:
Random read | print(sample_list[2]) | |
Random write | sample_list[2]=“James” | List is mutable i.e., the above statement will rewrite the existing value at index position 2 with “James”. |
Other operations:
Adding an element to the end of the list | sample_list.append(“James”) | List need not have a fixed size, it can grow dynamically |
Concatenating two lists | new_list=[“Henry”,”Tim”]sample_list+=new_listsample_list=sample_list+new_list | sample_list+=new_list, concatenates new_list to sample_list sample_list=sample_list+new_list, creates a new list named sample_list containing the concatenated elements from the original sample_list and new_list |
Iterating throw the List
1.for index in range(0,len(list_of_airlines)):
print(list_of_airlines[index])
2.for airline in list_of_airlines:
print(airline)
Program:
list_of_airlines=[“AI”,”EM”,”BA”]
airline=”AI”
if airline in list_of_airlines:
print(“Airline found”)
else:
print(“Airline not found”)
Output:
Airline found
Python tuple datatype
A tuple is an ordered sequence of items same as a list. The only difference is that tuples are immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than lists as they cannot change dynamically.
It is defined within parentheses () where items are separated by commas.
Tuples are immutable and the elements are READ-ONLY.
Creating a tuple | lunch_menu=(“Welcome Drink”,”Veg Starter”,”Non-Veg Starter”,”Veg Main Course”,”Non-Veg Main Course”,”Dessert”) | () are optional, a set of values separated by comma is also considered to be a tuple. sample_tuple=”A”,”B”,”C”Although () are optional, it is a good practice to have them for the readability of code. If we need to create a tuple with a single element, then we need to include a comma as shown below:sample_tuple=(“A”,) |
Random Write | lunch_menu[0]=”” | This will result in an error as tuple is immutable. Hence random write is not possible in tuple. |
Python String Datatype
In a program, not all values will be numerical. We will also have alphabetical or alpha numerical values. Such values are called strings.
Example:“Hello World”, “AABGT6715H”
String is represented by single or double quotes.
Just like list we can access each character of the string by its index.
String | “AABGT6715H” | |||||||||
Character | A | A | B | G | T | 6 | 7 | 1 | 5 | H |
Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Python set datatype
A set is an unordered group of values with no duplicate entries. Set can be created by using the keyword set or by using curly braces {}. set function is used to eliminate duplicate values in a list.
Creating a set | flight_set={500,520,600,345,520,634,600,500,200,200} | Removes the duplicates from the given group of values to create the set. |
Eliminating duplicates from a list | passengers_list=[“George”, “Annie”, “Jack”, “Annie”, “Henry”, “Helen”, “Maria”, “George”, “Jack”, “Remo”]unique_passengers=set(passengers_list) | set function – removes the duplicates from the list and returns a set |
Common elements between setA and setB | setA & setB | Creates a new set which has common elements from setA and setB |
Elements that are only in setA | setA – setB | Creates a new set which has only unique elements of setA |
Merges elements of setA and setB | setA | setB | Creates a new set which has all the elements of setA and setB |
Python Dictionary
Dictionary is an unordered collection of key-value pairs.
It is generally used when we have a huge amount of data.
Dictionaries are mutable
Creating a dictionary | crew_details={ “Pilot”:”Kumar”,”Co-pilot”:”Raghav”,”Head-Strewardess”:”Malini”,”Stewardess”:”Mala” } | First element in every pair is the key and the second element is the value. |
Accessing the value using key | crew_details[“Pilot”] | This will return the corresponding value for the specified key |
Iterating through the dictionary | for key,value in crew_details.items(): print(key,”:”,value) | items function gives both key and value, which can be used in a for loop. |
You may also like these:
Thanks for reading this, if you find this article helpful please leave your feedback and share it with your friends as well.
Stay connected and stay tuned.
GIPHY App Key not set. Please check settings