Python List Data Structure In Depth - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In Python, If we want to represent a group of values as a single entity, then we should go for Python List data structure.
Python’s List Data structure is having the below characteristics.
Python List is a mutable sequence of characters, typically used to store collections of similar items.
List preserves the Insertion order.
Python List allows duplicate elements.
Python List is mutable, i.e. once we create a list, it can be modified at any time.
Python List is considered to be a dynamic because based on our requirement it will grow and shrink in size.
We can traverse the list in both the directions that are left to right and right to left.
Since the Python List is an index based data structure, we can traverse the list by using indexes.
A positive index can be used to traverse from left to right, and a negative index used to traverse from right to left.
We can create a list by using [] open and close brackets.
list=[10,20,30,40]
print(type(list))
The above list contains values from 10 to 40 since these values enclosed with [] brackets, python considers it as a list type.
Output:
<class 'list'>
As Python List is an index based data structure, we can update the list elements using its index position.
list = [10,20,50,30,60,40]
print("Before Updation : ",list)
list[2] = "A"
print("After Updation : ",list)
The above program is to update the 2nd position of the list element.
Output:
Before Updation :  [10, 20, 50, 30, 60, 40]
After Updation :  [10, 20, 'A', 30, 60, 40]
You can remove the list elements in two different ways.
remove() function is used to remove the list element by value.
del keyword is used to delete the list element by index.
remove() :
It removes the first occurrence of the given value from the list.
list = [10,20,50,30,60,40,10]
print("Before : ",list)
list.remove(10)
print("After Deletion : ",list)
Output:
Before :  [10, 20, 50, 30, 60, 40, 10]
After Deletion :  [20, 50, 30, 60, 40, 10]
del keyword:
It deletes the element in a list by index position.
list = [10,20,50,30,60,40,10]
print("Before : ",list)
del list[3]
print("After Deletion : ",list)

Output:
Before Updation :  [10, 20, 50, 30, 60, 40, 10]
After Updation :  [10, 20, 50, 60, 40, 10]
You can access elements of the list either by using an index or by using slice operator (:)
As Python list is an index based data structure, we can get the list items using index itself.
A list follows the zero-based index, i.e. the index of the first element is zero.
List supports both +ve and -ve indexes.
+ve index meant for left right and -ve index indicated for the right to left traversing.
Python Index Representation :
Example:
list = [10,20,50,30,40]
print(list[0])
print(list[-1])
print(list[4])

Output:
10
40
40
We can access the list elements like between the indexes. The slice operator helps us to read values from the list for a given index range.
Syntax : 
list[start:end:step]
Start – indicates that the index position, where the real slice has to start, the default value is 0.
End – indicates that the index position, where the slicing has to end, the default value is the length of the list.
Step – is an increment value; the default increment value is 1.
Example:
list1 = (10,20,50,30,40,60,70,80,90)
print("Between 2 and 7 indexes increment by 1 : ",list1[2:7:1])
print("Between 2 and 7 indexes increment by 2 : ",list1[2:7:2])
print("Between 2 and 7 indexes : ",list1[2:7])
Output :
Between 2 and 7 indexes increment by 1 :  (50, 30, 40, 60, 70)
Between 2 and 7 indexes increment by 2 :  (50, 40, 70)
Between 2 and 7 indexes :  (50, 30, 40, 60, 70)
Note: start includes the index value whereas end excludes the index value.
list = [10,20,50,30,40,60,70,80,90]
# Using For loop
for i in list:
    print(i)

#Using while loop
i=0
while i<len(list):
    print(list[i])
    i=i+1

Both logics will give the same output.
Here are some of the critical functions in List in Python.
len()
len() function returns the number of elements present in the list.
list = [10,20,50,30,40,60,70,80,90]
print("Length of the list : ",len(list))
Output :
Length of the list : 9
count()
The count() function returns the number of occurrences of the specified item in the list.
list= [1,2,4,3,3,5,5,6,3,9,9,8]
print(list.count(3))
print(list.count(5))
print(list.count(9))
Output :
3
2
2
index()
It returns the index of the first occurrence of the given item.
list= [1,2,4,3,3,5,5,6,3,9,9,8]
print(list.index(3))
print(list.index(5))
print(list.index(9))
Output:
3
5
9
Note: If the specified element not present in the list then the index() function throws an error like ValueError: ‘ ‘ is not in the list.
clear() : The clear() function is used to clear the elements inside a list.
list1= [10,20,30,40,50]
print(list1)
list1.clear()
print("After clearing List : ",list1)
Output:
[10, 20, 30, 40, 50]
After clearing List :  []
max() : The max() function is used to get the max value from the list.
list1= [10,20,30,40,50]
print(max(list1))
Output:
50
append()
append() function is used to add the item to the list at the end of the list.
list= []
list.append("C")
list.append("H")
list.append("A")
list.append("N")
list.append("D")
list.append("R")
list.append("A")
print(list)
Output:
['C', 'H', 'A', 'N', 'D', 'R', 'A']
insert()
The insert() function is used to insert an item to the list at a given index position.
list= [1,2,3,4,5,6]
# inserting 20 at 1st index
list.insert(1,20)
# inserting 50 at 5th index
list.insert(5,50)
print(list)
Output:
[1, 20, 2, 3, 4, 50, 5, 6]
Note: If the given index is greater than the max size of the list, then the element will be inserted at the last position. Similarly, if the specified index is smaller than the min size of the list, then the item will be added at first position.
Difference between append() and list()


extend()
The extend() function is used to add all items in a list to another list at a time.
list= ['o','n','l','i','n','e']
list2= ['t','u','t','o','r','i','a','l','s']
list3= ['p','o','i','n','t']
list.extend(list2)
list.extend(list3)
print(list)
Output:
['o', 'n', 'l', 'i', 'n', 'e', 't', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't']
remove()
remove() function is used to remove a specific item from the list. If the specified item found in multiple times, then it will remove the first occurrence.
list= [10,20,30,40,10,20]
list.remove(20)
print(list)
Output:
[10, 30, 40, 10, 20]
pop()
pop() function is used to remove the last element of the list and returns the popped item.
pop(index) function is used to remove the item based on the given index.
list= [10,20,30,40,10,20,30]
print(list.pop())
print(list.pop())

print(list)
# pop index based
print(list.pop(2))
print(list)
Output:
30
20
[10, 20, 30, 40, 10]
30
[10, 20, 40, 10]
Note: Usually, append, and pop functions are used to implement a stack data structure.
Differences between remove() and pop()


Note: List is a dynamic data structure, i.e. based on our requirement it can grow and shrink. the append(), insert() and extend() functions are used to increase the size of the list whereas remove() and pop() functions are used to shrink the size.
reverse()
The reverse() function is used to make the list elements in reverse order.
list= [10,20,30,40,50]
list.reverse()
print(list)

Output:
[50, 40, 30, 20, 10]
sort()
In a list, by default insertion order is preserved, if we want to sort the elements of the list according to default natural order, then we can use the sort() method.
If a List contains only numerical, the default natural sorting order will be Ascending order.
If a List contains only strings, then the default natural sorting order will be Alphabetical order.
sort() method apply on List if the List contains homogenous elements. Otherwise, it will give TypeError.
list= [10,30,20,50,80,5]
list.sort()
print(list)

list2= ["CHANDRA","SHEKAHR","GOKA"]
list2.sort()
print(list2)

list3= [50,20,'A','B']
list3.sort()
print(list3)
Output:
[5, 10, 20, 30, 50, 80]
['CHANDRA', 'GOKA', 'SHEKAHR']
Traceback (most recent call last):
    list3.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
Note: In Python2 sort() function supports various elements to sort.
We can also sort a List in reverse of default natural sorting order by using the reverse=true argument.
list= [10,30,20,50,80,5]
list.sort(reverse=True)
print(list)
Output:
[80, 50, 30, 20, 10, 5]
The process of assigning an existing list reference to another reference variable is called aliasing.
list1= [10,20,30,40,50]
list2 = list1
print(id(list1))
print(id(list2))

Output:
2268420908872
2268420908872
The problem with this approach is, if we change one reference value, then it automatically reflected another reference too.
list1= [10,20,30,40,50]
list2 = list1
list1[1]=100
print(list1)
print(list2)

Output:
[10, 100, 30, 40, 50]
[10, 100, 30, 40, 50]
To overcome this problem, we should use List Cloning.
The process of creating a duplicate independent object is called cloning.
In Python, we can create a clone object by using slice (:) operator or copy() function.
List Cloning using slice operator :
list1= [10,20,30,40,50]
list2 = list1[:]
list1[1]=100
print(list1)
print(list2)
Output:
[10, 100, 30, 40, 50]
[10, 20, 30, 40, 50]
List Cloning using copy() function:
list1= [10,20,30,40,50]
list2 = list1.copy()
list1[1]=100
print(list1)
print(list2)
Output:
[10, 100, 30, 40, 50]
[10, 20, 30, 40, 50]
In Python, we can compare two lists using comparison operators.
list1= ['APPLE','BANANA','GRAPES']
list2 = ['APPLE','BANANA','GRAPES']
list3 = ['Apple','Banana','Grapes']

print(list1 == list2)
print(list1 == list3)
print(list1 != list3)
Output:
True
False
True
Note: Whenever we compare the list using comparison operators like (== and !=) the List object considers the following scenarios to examine the elements.
The number of elements present in a list
The order of elements
The content of List (Case sensitivity)
The List can also be compared using relational operators (<,<=,> and >=).
In the case of relational operators, the comparison happens only on the first element of the list; the remaining elements should be ignored.
list1= [10,20,30,40,50]
list2 = [20,5,4,3,2]

print(list1 > list2)
print(list1 >= list2)
print(list1 < list2)
print(list1 <= list2)
Output:
False
False
True
True
We can test a specific element present in a list or not using membership operators.
in
not in
list1= [10,20,30,40,50]

print(30 in list1)
print(100 in list2)
print(20 not in list2)

Output:
True
False
False
We can concatenate two lists using the ‘+’ operator.
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
print("New List : ",list1+list2)
Output:
New List :  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
You can repeat the list elements multiple times using the ‘*’ operator.
list1 = [1,2,3,4,5]
print("New List : ",list1*2)
Output:
New List :  [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
Reference:
Python List Data structure
Happy Learning 🙂

How to merge two lists in Python
Python Tuple Data Structure in Depth
Python – Print different vowels present in a String
Python Set Data Structure in Depth
How to Remove Spaces from String in Python
What are the different ways to Sort Objects in Python ?
Java 8 How to get common elements from two lists
How to Create or Delete Directories in Python ?
Python – How to merge two dict in Python ?
What are the List of Python Keywords
What are different Python Data Types
Python – How to remove duplicate elements from List
How to Convert Python List Of Objects to CSV File
Features of Python Language
Modes of Python Program

How to merge two lists in Python
Python Tuple Data Structure in Depth
Python – Print different vowels present in a String
Python Set Data Structure in Depth
How to Remove Spaces from String in Python
What are the different ways to Sort Objects in Python ?
Java 8 How to get common elements from two lists
How to Create or Delete Directories in Python ?
Python – How to merge two dict in Python ?
What are the List of Python Keywords
What are different Python Data Types
Python – How to remove duplicate elements from List
How to Convert Python List Of Objects to CSV File
Features of Python Language
Modes of Python Program
 


Δ
 Python – Introduction
 Python – Features
 Python – Install on Windows
 Python – Modes of Program
 Python – Number System
 Python – Identifiers
 Python – Operators
 Python – Ternary Operator
 Python – Command Line Arguments
 Python – Keywords
 Python – Data Types
 Python – Upgrade Python PIP
 Python – Virtual Environment
 Pyhton – Type Casting
 Python – String to Int
 Python – Conditional Statements
 Python – if statement
 Python – *args and **kwargs
 Python – Date Formatting
 Python – Read input from keyboard
 Python – raw_input
 Python – List In Depth
 Python – List Comprehension
 Python – Set in Depth
 Python – Dictionary in Depth
 Python – Tuple in Depth
 Python – Stack Datastructure
 Python – Classes and Objects
 Python – Constructors
 Python – Object Introspection
 Python – Inheritance
 Python – Decorators
 Python – Serialization with Pickle
 Python – Exceptions Handling
 Python – User defined Exceptions
 Python – Multiprocessing
 Python – Default function parameters
 Python – Lambdas Functions
 Python – NumPy Library
 Python – MySQL Connector
 Python – MySQL Create Database
 Python – MySQL Read Data
 Python – MySQL Insert Data
 Python – MySQL Update Records
 Python – MySQL Delete Records
 Python – String Case Conversion
 Howto – Find biggest of 2 numbers
 Howto – Remove duplicates from List
 Howto – Convert any Number to Binary
 Howto  – Merge two Lists
 Howto – Merge two dicts
 Howto – Get Characters Count in a File
 Howto – Get Words Count in a File
 Howto – Remove Spaces from String
 Howto –  Read Env variables
 Howto – Read a text File
 Howto – Read a JSON File
 Howto –  Read Config.ini files
 Howto – Iterate Dictionary
 Howto – Convert List Of Objects to CSV
 Howto – Merge two dict in Python
 Howto – create Zip File
 Howto – Get OS info
 Howto – Get size of Directory
 Howto – Check whether a file exists
 Howto –  Remove key from dictionary
 Howto – Sort Objects
 Howto – Create or Delete Directories
 Howto – Read CSV File
 Howto – Create Python Iterable class
 Howto – Access for loop index
 Howto – Clear all elements from List
 Howto – Remove empty lists from a List
 Howto – Remove special characters from String
 Howto – Sort dictionary by key
 Howto – Filter a list