Python List, Tuple and Dictionary

 Python List

List in python is implemented to store the sequence of various type of data. However, python contains six data types that are capable to store the sequences but the most common and reliable type is list.
A list can be defined as a collection of values or items of different types. The items in the list are separated with the comma (,) and enclosed with the square brackets [].
A list can be defined as follows.

  1. L1 = ["John"102"USA"]  
  2. L2 = [123456]  
  3. L3 = [1"Ryan"]  

If we try to print the type of L1, L2, and L3 then it will come out to be a list.

Lets consider a proper example to define a list and printing its values.

  1. emp = ["John"102"USA"]   
  2. Dep1 = ["CS",10];  
  3. Dep2 = ["IT",11];  
  4. HOD_CS = [10,"Mr. Holding"]  
  5. HOD_IT = [11"Mr. Bewon"]  
  6. print("printing employee data...");  
  7. print("Name : %s, ID: %d, Country: %s"%(emp[0],emp[1],emp[2]))  
  8. print("printing departments...");  
  9. print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID: %s"%(Dep1[0],Dep2[1],Dep2[0],Dep2[1]));  
  10. print("HOD Details ....");  
  11. print("CS HOD Name: %s, Id: %d"%(HOD_CS[1],HOD_CS[0]));  
  12. print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]));  
  13. print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT));   

Output:

printing employee data...
Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class 'list'> <class 'list'> <class 'list'> <class 'list'> <class 'list'>

List indexing and splitting

The indexing are processed in the same way as it happens with the strings. The elements of the list can be accessed by using the slice operator [].

The index starts from 0 and goes to length - 1. The first element of the list is stored at the 0th index, the second element of the list is stored at the 1st index, and so on.

Consider the following example.
Python Lists
Unlike other languages, python provides us the flexibility to use the negative indexing also. The negative indices are counted from the right. The last element (right most) of the list has the index -1, its adjacent left element is present at the index -2 and so on until the left most element is encountered.
Python Lists

Updating List values

Lists are the most versatile data structures in python since they are immutable and their values can be updated by using the slice and assignment operator.
Python also provide us the append() method which can be used to add values to the string.
Consider the following example to update the values inside the list.

  1. List = [123456]   
  2. print(List)   
  3. List[2] = 10;  
  4. print(List)  
  5. List[1:3] = [8978]   
  6. print(List)  

Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]

The list elements can also be deleted by using the del keyword. Python also provides us the remove() method if we do not know which element is to be deleted from the list.
Consider the following example to delete the list elements.

  1. List = [0,1,2,3,4]   
  2. print(List)  
  3. del List[0]  
  4. print(List)   
  5. del List[3]  
  6. print(List)  

Output:

[0, 1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3]

Python List Built-in functions

Python provides the following built-in functions which can be used with the lists.

SNFunctionDescription
1cmp(list1, list2)It compares the elements of both the lists.
2len(list)It is used to calculate the length of the list.
3max(list)It returns the maximum element of the list.
4min(list)It returns the minimum element of the list.
5list(seq)It converts any sequence to the list.

Python List built-in methods

SNFunctionDescription
1list.append(obj)The element represented by the object obj is added to the list.
2list.clear()It removes all the elements from the list.
3List.copy()It returns a shallow copy of the list.
4list.count(obj)It returns the number of occurrences of the specified object in the list.
5list.extend(seq)The sequence represented by the object seq is extended to the list.
6list.index(obj)It returns the lowest index in the list that object appears.
7list.insert(index, obj)The object is inserted into the list at the specified index.
8list.pop(obj=list[-1])It removes and returns the last object of the list.
9list.remove(obj)It removes the specified object from the list.
10list.reverse()It reverses the list.
11list.sort([func])It sorts the list by using the specified compare function if given.


Python Tuple

Python Tuple is used to store the sequence of immutable python objects. Tuple is similar to lists since the value of the items stored in the list can be changed whereas the tuple is immutable and the value of the items stored in the tuple can not be changed.
A tuple can be written as the collection of comma-separated values enclosed with the small brackets. A tuple can be defined as follows.

  1. T1 = (101"Ayush"22)  
  2. T2 = ("Apple""Banana""Orange")   

Example

  1. tuple1 = (102030405060)  
  2. print(tuple1)  
  3. count = 0  
  4. for i in tuple1:  
  5.     print("tuple1[%d] = %d"%(count, i));  

Output:

(10, 20, 30, 40, 50, 60)
tuple1[0] = 10
tuple1[0] = 20
tuple1[0] = 30
tuple1[0] = 40
tuple1[0] = 50
tuple1[0] = 60

Tuple indexing and splitting

The indexing and slicing in tuple are similar to lists. The indexing in the tuple starts from 0 and goes to length(tuple) - 1.
The items in the tuple can be accessed by using the slice operator. Python also allows us to use the colon operator to access multiple items in the tuple.
Consider the following image to understand the indexing and slicing in detail.
Python Tuple
Unlike lists, the tuple items can not be deleted by using the del keyword as tuples are immutable. To delete an entire tuple, we can use the del keyword with the tuple name.
Consider the following example.

  1. tuple1 = (123456)  
  2. print(tuple1)  
  3. del tuple1[0]  
  4. print(tuple1)  
  5. del tuple1  
  6. print(tuple1)  

Output:

(1, 2, 3, 4, 5, 6)
Traceback (most recent call last):
  File "tuple.py", line 4, in <module>
    print(tuple1)
NameError: name 'tuple1' is not defined


Like lists, the tuple elements can be accessed in both the directions. The right most element (last) of the tuple can be accessed by using the index -1. The elements from left to right are traversed using the negative indexing.
Consider the following example.

  1. tuple1 = (12345)  
  2. print(tuple1[-1])  
  3. print(tuple1[-4])  

Output:

5
2

Python Tuple inbuilt functions

SNFunctionDescription
1cmp(tuple1, tuple2)It compares two tuples and returns true if tuple1 is greater than tuple2 otherwise false.
2len(tuple)It calculates the length of the tuple.
3max(tuple)It returns the maximum element of the tuple.
4min(tuple)It returns the minimum element of the tuple.
5tuple(seq)It converts the specified sequence to the tuple.


Python Dictionary

Dictionary is used to implement the key-value pair in python. The dictionary is the data type in python which can simulate the real-life data arrangement where some specific value exists for some particular key.
In other words, we can say that a dictionary is the collection of key-value pairs where the value can be any python object whereas the keys are the immutable python object, i.e., Numbers, string or tuple.
Dictionary simulates Java hash-map in python.

Creating the dictionary

The dictionary can be created by using multiple key-value pairs enclosed with the small brackets () and separated by the colon (:). The collections of the key-value pairs are enclosed within the curly braces {}.
The syntax to define the dictionary is given below.

  1. Dict = {"Name""Ayush","Age"22}  

In the above dictionary Dict, The keys Name, and Age are the string that is an immutable object.
Let's see an example to create a dictionary and printing its content.

  1. Employee = {"Name""John""Age"29"salary":25000,"Company":"GOOGLE"}  
  2. print(type(Employee))  
  3. print("printing Employee data .... ")  
  4. print(Employee)  

Output

<class 'dict'>
printing Employee data .... 
{'Age': 29, 'salary': 25000, 'Name': 'John', 'Company': 'GOOGLE'}

Accessing the dictionary values

We have discussed how the data can be accessed in the list and tuple by using the indexing.
However, the values can be accessed in the dictionary by using the keys as keys are unique in the dictionary.
The dictionary values can be accessed in the following way.

  1. Employee = {"Name""John""Age"29"salary":25000,"Company":"GOOGLE"}  
  2. print(type(Employee))  
  3. print("printing Employee data .... ")  
  4. print("Name : %s" %Employee["Name"])  
  5. print("Age : %d" %Employee["Age"])  
  6. print("Salary : %d" %Employee["salary"])  
  7. print("Company : %s" %Employee["Company"])  

Output:

<class 'dict'>
printing Employee data .... 
Name : John
Age : 29
Salary : 25000
Company : GOOGLE

Python provides us with an alternative to use the get() method to access the dictionary values. It would give the same result as given by the indexing.

Updating dictionary values

The dictionary is a mutable data type, and its values can be updated by using the specific keys.
Let's see an example to update the dictionary values.

  1. Employee = {"Name""John""Age"29"salary":25000,"Company":"GOOGLE"}  
  2. print(type(Employee))  
  3. print("printing Employee data .... ")  
  4. print(Employee)  
  5. print("Enter the details of the new employee....");  
  6. Employee["Name"] = input("Name: ");  
  7. Employee["Age"] = int(input("Age: "));  
  8. Employee["salary"] = int(input("Salary: "));  
  9. Employee["Company"] = input("Company:");  
  10. print("printing the new data");  
  11. print(Employee)  

Output:

<class 'dict'>
printing Employee data .... 
{'Name': 'John', 'salary': 25000, 'Company': 'GOOGLE', 'Age': 29}
Enter the details of the new employee....
Name: David
Age: 19
Salary: 8900
Company:JTP
printing the new data
{'Name': 'David', 'salary': 8900, 'Company': 'JTP', 'Age': 19}

Deleting elements using del keyword

The items of the dictionary can be deleted by using the del keyword as given below.

  1. Employee = {"Name""John""Age"29"salary":25000,"Company":"GOOGLE"}  
  2. print(type(Employee))  
  3. print("printing Employee data .... ")  
  4. print(Employee)  
  5. print("Deleting some of the employee data")   
  6. del Employee["Name"]  
  7. del Employee["Company"]  
  8. print("printing the modified information ")  
  9. print(Employee)  
  10. print("Deleting the dictionary: Employee");  
  11. del Employee  
  12. print("Lets try to print it again ");  
  13. print(Employee)  

Output:

<class 'dict'>
printing Employee data .... 
{'Age': 29, 'Company': 'GOOGLE', 'Name': 'John', 'salary': 25000}
Deleting some of the employee data
printing the modified information 
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again 
Traceback (most recent call last):
  File "list.py", line 13, in <module>
    print(Employee)
NameError: name 'Employee' is not defined

Iterating Dictionary

A dictionary can be iterated using the for loop as given below.

Example 1

# for loop to print all the keys of a dictionary

  1. Employee = {"Name""John""Age"29"salary":25000,"Company":"GOOGLE"}  
  2. for x in Employee:  
  3.     print(x);  

Output:

Name
Company
salary
Age

Built-in Dictionary functions

The built-in python dictionary methods along with the description are given below.

SNFunctionDescription
1cmp(dict1, dict2)
It compares the items of both the dictionary and returns true if the first dictionary values are greater than the second dictionary, otherwise it returns false.
2len(dict)It is used to calculate the length of the dictionary.
3str(dict)It converts the dictionary into the printable string representation.
4type(variable)It is used to print the type of the passed variable.

Built-in Dictionary methods

The built-in python dictionary methods along with the description are given below.

SNMethodDescription
1dic.clear()It is used to delete all the items of the dictionary.
2dict.copy()It returns a shallow copy of the dictionary.
3dict.fromkeys(iterable, value = None, /)
Create a new dictionary from the iterable with the values equal to value.
4dict.get(key, default = "None")
It is used to get the value specified for the passed key.
5dict.has_key(key)
It returns true if the dictionary contains the specified key.
6dict.items()It returns all the key-value pairs as a tuple.
7dict.keys()It returns all the keys of the dictionary.
8dict.setdefault(key,default= "None")
It is used to set the key to the default value if the key is not specified in the dictionary
9dict.update(dict2)
It updates the dictionary by adding the key-value pair of dict2 to this dictionary.
10dict.values()It returns all the values of the dictionary.
11len()
12popItem()
13pop()
14count()
15index()

Comments

Popular posts from this blog

Python File Handling & Exception Handling