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.
There are many collection data types which are supported by Python.
Let’s start by exploring one of the most common collection data type – list. List can be used to store a group of elements together in a sequence.
If we want to store the ticket numbers allocated to each passenger traveling in a flight, Instead of using separate variable for each ticket number, we can use a list as shown below.
In case of having different variables for each ticket number, variables will be stored in separate memory locations. Whereas in case of list, the elements will be stored in contiguous memory locations.
Each element in the list has a position in the list known as an index. The list index starts from zero. It’s like having seat numbers starting from 0!
Element | 78808 | 26302 | 93634 | 13503 | 48306 |
Index | 0 | 1 | 2 | 3 | 4 |
If seat number 2 is allocated to the passenger with ticket number 93634, the passenger can directly go to seat number 2 without having to go through other seats. Similarly, index positions actually help us to directly access a value from the list.
list_name[index] can be used to directly access the list element at the mentioned index position.
if we want to allocate a different passenger to seat number 3, we can do it as ticket_list[3]=13504. Thus, in addition to using the index to access an element directly, we can also use it to directly modify an element in the list.
Just like how we cannot allocate 101st seat to a passenger in a 100 seat plane, we cannot access values beyond the total number of elements in the list.
For example: print(ticket_list[5]) will result in index out of bound error.
Let’s see how to create a list in Python and perform some operations on it.
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_list sample_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 Observe this difference while visualizing |
List - Iteration and Sequential access
As elements are stored sequentially in a list, we can use a loop to access the elements.
Try out the below code in Python playground and observe the different ways of accessing the elements in a list sequentially.
list_of_airlines=["AL1","AL2","AL3"] print("Iterating the list using range()") for index in range(0,len(list_of_airlines)): print(list_of_airlines[index]) print("Iterating the list using keyword in") for airline in list_of_airlines: print(airline)
If we just want to find out whether an element is there in a list, we need not iterate through the list. Instead we can check using if..in syntax. Try out the code and observe the results.
list_of_airlines=["AL1","AL2","AL3"] airline="AL3" if airline in list_of_airlines: print("Airline found") else: print("Airline not found")
List - Slicing
Assume that the name of the airlines operating from an airport are stored in a list as shown below.
Suppose we need to extract the airlines from the 1st to the 3rd index positions in the list. How can we do that?
List of Airlines | AL1 | AL2 | AL3 | AL4 | AL5 |
Index | 0 | 1 | 2 | 3 | 4 |
Negative Index | -5 | -4 | -3 | -2 | -1 |
Python offers a simple solution in the form of slicing:
sub_list=list_of_airlines[1:4]
The above line provides a sub list from index position 1 to 3 (i.e., 1 to (4-1)).
For example: To fetch the second last airline in the list, we can write list_of_airlines[-2]. This is equivalent to list_of_airlines[len(list_of_airlines)-2].
Indices may also be considered negative as shown above. This is normally used to count from right. Negative indices can also be used for slicing.
For example: list_of_airlines[-4:-1] will give us the same output as list_of_airlines[1:4]
Suppose it is mandatory to have the following types of food in the lunch menu of the passengers.
Welcome Drink, Veg Starter, Non-Veg Starter, Veg Main Course, Non-Veg Main Course, Dessert
How can we store it such that no one can modify the elements?
Of course, we can use a list but anybody can modify an element in the list. This is where we can use another collection data type known as tuple.
Like list, tuple can also store a sequence of elements but the value of the elements cannot be changed. (i.e. tuples are IMMUTABLE). Elements can be homogeneous or heterogeneous but they 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 readability of code. |
Random Write | lunch_menu[0]=“” | This will result in an error as tuple is immutable. Hence random write is not possible in tuple. |
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"
Each value in a string is called a character. Just like list elements, we can access the characters in a string based on its index position.
String | “AABGT6715H” | |||||||||
---|---|---|---|---|---|---|---|---|---|---|
Character | A | A | B | G | T | 6 | 7 | 1 | 5 | H |
index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
In Python, string is a data type and anything enclosed in a single quote or double quote is considered to be a string. All the remaining operations are similar to lists. But like tuple, strings are also IMMUTABLE.
Try out the below code in python playground and observe how to create strings and how to perform operations on strings.
#Creating a string pancard_number="AABGT6715H" #Length of the string print("Length of the PAN card number:", len(pancard_number)) #Concatenating two strings name1 ="PAN " name2="card" name=name1+name2 print(name) print("Iterating the string using range()") for index in range(0,len(pancard_number)): print(pancard_number[index]) print("Iterating the string using keyword in") for value in pancard_number: print(value) print("Searching for a character in string") if "Z" in pancard_number: print("Character present") else: print("Character is not present") #Slicing a string print("The numbers in the PAN card number:", pancard_number[5:9]) print("Last but one 3 characters in the PAN card:",pancard_number[-4:-1]) pancard_number[2]="A" #This line will result in an error, i.e., string is immutable print(pancard_number)
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 set A and set B | set A & set B | Creates a new set which has common elements from set A and set B |
Elements that are only in set A | set A - set B | Creates a new set which has only unique elements of set A |
Merges elements of set A and set B | set A | set B | Creates a new set which has all the elements |
A dictionary can be used to store an unordered collection of key-value pairs. The key should be unique and can be of any data type. Like lists, dictionaries are mutable.
Creating a dictionary | crew_details= { "Pilot":"John", "Co-pilot":"Jem", "Head-Strewardess":"Mini", "Stewardess":"Jerry" } | 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. |
All Rights Reserved. © 2024 BookOfNetwork