Python List Data Structure In Depth

By | 2018-04-15T17:46:45+00:00 April 4th, 2018|Python|0 Comments

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 List Data Structure :

Python’s List Data structure having the below characteristics.

  • Python List is an mutable sequence of characters, typically used to store collections of homogeneous 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 modify at any time.
  • Python List is consider 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 is 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 used to traverse from left to right and a negative index used to traverse from right to left.

Creating Python List Object:

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'>

Updating List Elements:

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]

Deleting Elements from a List :

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 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]

How to Access List Elements:

You can access elements of the list either by using index or by using slice operator (:)

Accessing List uisng index :

  • As Python list is an index based data structure, we can access the list items using index itself.
  • List follows zero based index, i.e. index of the first element is zero.
  • List supports both +ve and -ve indexes.
  • +ve index meant for left right and -ve index meant for right to left traversing.

Python Index Representation :

Python List Data Structure Indexing

Example:

list = [10,20,50,30,40]
print(list[0])
print(list[-1])
print(list[4])

Output:

10
40
40

Accessing List uisng slice (:):

We can access the list elements like between the indexes. The slice operator helps us to read values from the list for given index range.

Syntax : 

list[start:end:step]
  • start – indicates that the index position, where the atual slice has to be start, default value is 0.
  • end – indicates that the index position, where the slicing has to be end, default value is length of the list.
  • step – is an increment value, defa lt 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.

Traversing List using Loops :

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.

List inbuilt Functions :

Here are the some of important functions in List in Python.

Getting information about List :

  • 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 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 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 error like : ValueError: ‘ ‘ is not in 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

Manipulating List Elements:

  • 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 max size of the list, then the element will be inserted at the last position. Similarly, if the specified index is smaller than min size of the list, then the element will be inserted at first position.

Difference between append() and list()

append() insert()
It will add the element in list at lastposition It will add the element in list at a given index position.

  • 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 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 stack data structure.

Differences between remove() and pop()

remove() pop()
remove() function is used to remove the special element from list. pop() function is used to remove the last element from the list
remove() function doesn’t return any value pop() function returns removed element.
If given element not found in the list the remove() function throws VALUE error pop() method will throw error if the list is empty.

Note: List is a dynamic data structure, i.e. based on our requirement it can be 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.

Ordering the List Elements :

  • 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 list bydefault 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, iff the List contains homogenious 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() funtion supports heterogeneous 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]

Aliasing and Cloning of List Object :

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))

Python List Data Struture

Output:

2268420908872
2268420908872

The problem with this approuch is, if we change one reference value, then it automatically reflected to another reference too.

list1= [10,20,30,40,50]
list2 = list1
list1[1]=100
print(list1)
print(list2)

Python List DataStructure 2

Output:

[10, 100, 30, 40, 50]
[10, 100, 30, 40, 50]

To overcome with this problem we should use List Cloning.

List Cloning :

The process of creating duplicate indipendent 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]

How to compare two Lists:

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 following scenarios to compare 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 opertors, the comparison happens only on first element of the list, the remainig 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

Checking a Specific Element exist in List:

We can check 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

Concatenating two Lists:

We can concatenate two lists using +’ 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]

Repeating List Elements:

You can repeate the list elements multiple times using ‘*’ 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:)

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment