List Datatype

The list is nothing but a consecutive collection of related items/words.

Representing a group of values as a single entity where the order is important and allows duplicate values is called List Datatype, which can be represented by using the square bracket[] and separating the values by a comma.

L=[5,10,20,30,10,'apple']

List=[5,10,20,30,10,'apple']
print(List)
print(type(List))
#The output is:
[5, 10, 20, 30, 10, 'apple']
<class 'list'>

data-type-of-list

The Properties of List Datatypes are:

  • Order is preserved
  • Duplicate values are allowed
  • Should be mentioned in square brackets
  • Heterogeneous objects are allowed
  • Indexing concept is applicable
  • Slicing concept is applicable in List data type
  • We can Add and Remove the elements from the List
  • And List is Mutable

If we want to add any new element to the list then we can add by using the append() method

where List= [5,10,20,30,10, "apple"]

if you want to add mango to the list then l.append("mango")

List=[10,20,30,10,"apple"]
print(List)
List.append("mango")
print(List)
List.append(11)
List.append(33)
print(List)
#The output is:
[10, 20, 30, 10, 'apple']
[10, 20, 30, 10, 'apple', 'mango']
[10, 20, 30, 10, 'apple', 'mango', 11, 33]

In the same way, we can also remove an element from the list by using remove() method

List.remove(33)
print(List)
List.remove("mango")
print(List)
#The output is:
[10, 20, 30, 10, 'apple', 'mango', 11]
[10, 20, 30, 10, 'apple', 11]

removing-element-from-the-list

The list is a Mutable Data type, hence we can add an element to the specific index by passing an argument.

List=[10,2.0,30,50,40]
print(List)
List[0]=5
print(List)
##the output is:
[10, 2.0, 30, 50, 40]
[5, 2.0, 30, 50, 40]

Creating a List Objects

We can create different types of list objects

1. If we do not know the list arguments, then we can create an empty list

List=[ ]
print(type(List))
##The output is:
<class 'list'>

empty-list-one

2. If we know the List arguments, then we can create the list by enclosing the list arguments inside the square brackets and separating by a comma.

List=[20,90,67,30]
print(type(List))
## the output is:
<class 'list'>

list-with-arguments-one

3.Creating a list by dynamically entering the list arguments from the keyboard

List=eval(input("Enter the list element"))
print(type(List))
##The output is:
Enter the list element:[10,20,30]
<class 'list'>

creating-list-by-using-eval-function

4.By using the list() function, we can convert the tuple, a string and a range to list

Example 1: Converting string to list datatype

fruit=list('Apple')
print(fruit)
##The output is:
['A', 'p', 'p', 'l', 'e']

creating-list-by-dynamicaly-entering-elements

Example 2: Converting range datatype to list data type

data=list(range(0,10,2))
print(data)

converting-range-to-list

5. Creating a list by using the split() function, this function is applicable only in case of the string data type.

string="Learning python is easy"
List=string.split()
print(List)
##The output is:
['Learning', 'python', 'is', 'easy']

creating-list-by-using-split-function

Accessing the list elements by using the index and slice operator

We can access the list elements either by using the index operator or by using the slice operator.

By using Index Operator

  • The List supports for the zero-based index, the index of the first element is zero.
  • The list supports both positive indexing and negative indexing.
  • The positive indexing means forward direction(-->) or from left to right.
  • The negative indexing means, backward direction(<--) or from right to left.

Example:

List=[5,10,15,20,25]
print(List[0])
print(List[-1])
print(List[100])
##The output is:
5
25
Traceback (most recent call last):
  File "C:UsersAnup kumareclipse-workspaceFirstProjectPythonFirstPythonPackageFirstPythonModule.py", line 4, in <module>
    print(List[100])
IndexError: list index out of range

The output is:

accessing-list-elements-by-using-index-operator

By using the Slice operator

In string we have an operator is called Slice, which is nothing but a part of a string, in some cases, if we want to print a part of that string or a slice of that string then we will use this operator.

The syntax of the slice operator is

s[begin:end:step]

Begin: The integer where the beginning of a slicing object will start.
End: The integer until which the slicing will take place or slicing will stop.
Step: Integer which determines the increment between each index for slicing.

  • The step value can be either +ve or -ve
  • If the step value is +ve then, we have to consider from the begin to end-1 in Forward direction(From left to right)
  • If the step value is -ve then, we have to consider from the begin to end+1 in Backward direction(From right to left)
  • In the backward direction if the step value -1 then the result is always empty.
  • In the forward direction if the step value 0 then the result is always empty.
  • In Forward Direction:
    The default value for begin is 0
    The default value for the end is the length of the string
    The default value for step is +1
  • In Backward Direction:
    The default value for begin is -1
    The default value for the end is -(length of the string+1)
  • We can consider both +ve and -ve values for beginning and end index in case of forwarding and backward directions.

Example1:

List=[10,20,30,40,50,60,70,80,90,100]

The Diagrammatic representation of the above list is

diagramatic-representation-of-list

print(List[2:7])
print(List[2:7:2])
print(List[4: :2])
print(List[8:2:-2])
print(List[4:100])
print(List[4:0:2])
##The output is:
[30, 40, 50, 60, 70]
[30, 50, 70]
[50, 70, 90]
[90, 70, 50]
[50, 60, 70, 80, 90, 100]
[]

accessing-elements-by-using-slice-operator

List=[10,20,30,40,50,60,7,0,80,90,100]
print(List[ : : 1])
print(List[: : -1])
##The output is:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
[100, 90, 80, 70, 60, 50, 40, 30, 20, 10]

accessing-elements-by-using-slice-operator-one

Traversing of List Elements

Traverse: It is nothing traveling across.

Python provides the keyword called Traversing, which can be used to access each element in the list.

There different types of approaches are there to traverse the list elements

1.By using the while loop:

List=[0,1,2,3,4,5,6,7,8,9,10]
integer=0
while integer<len(List):
    print(List[integer])
    integer=integer+1
##The output is:
0
1
2
3
4
5
6
7
8
9
10
    

traversing-by-using-while-loop

2.By using for loop

List=[0,1,2,3,4,5,6,7,8,9,10]
for x in List:
    print(x)
##The output is:
0
1
2
3
4
5
6
7
8
9
10

traversing-by-using-for-loop

3.Display only Even numbers from the list

List=[0,1,2,3,4,5,6,7,8,9,10]
for x in List:
    if x%2==0:
        print(x)
##The output is:
0
2
4
6
8
10

displaying-only-even-number

4.Displaying the elements present in the list by using an index operator

List=[0,1,2,3,4,5,6,7,8,9,10]
integer=0
while integer<len(List):
    print("The element present at +ve index:{} and at -ve index:{} is:{}".format(integer,integer-len(List),List[integer]))
    integer=integer+1
##The output is:
The element present at +ve index:0 and at -ve index:-11 is:0
The element present at +ve index:1 and at -ve index:-10 is:1
The element present at +ve index:2 and at -ve index:-9 is:2
The element present at +ve index:3 and at -ve index:-8 is:3
The element present at +ve index:4 and at -ve index:-7 is:4
The element present at +ve index:5 and at -ve index:-6 is:5
The element present at +ve index:6 and at -ve index:-5 is:6
The element present at +ve index:7 and at -ve index:-4 is:7
The element present at +ve index:8 and at -ve index:-3 is:8
The element present at +ve index:9 and at -ve index:-2 is:9
The element present at +ve index:10 and at -ve index:-1 is:10

traversing-by-using-index-operator

Concatenation Operator for List

We can use the concatenation operator for adding the two lists

Example:

List_one=[1,2,3,4,5]
List_two=[6,7,8,9]
List_three=List_one+List_two
print(List_three)
##The output is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

concatenting-list-elements

If we try to add list with int value then, python will throw a type error

List_one=[10,20,30]
List_two=List_one+40
print(List_two)
##The output is:
Traceback (most recent call last):
  File "C:UsersAnup kumareclipse-workspaceFirstProjectPythonFirstPythonPackageFirstPythonModule.py", line 2, in <module>
    List_two=List_one+40
TypeError: can only concatenate list (not "int") to list

List-value-eror

To use the concatenation operator both the arguments must be of list datatypes

Repetition operator for List

To repeat the elements present inside the list for the specified number of times we use the repetition operator.

To use the repetition operator one argument must be of list type and another must be of int type.

Example:

List_one=[10,20,30]
List_two=List_one*2
print(List_two)
##The output is:
[10, 20, 30, 10, 20, 30]

repeating-list

Example2: If we try to repeat the list multiplying it with non-int type then, python will throw an error.

List_one=[10,20,30]
List_two=List_one*2.0
print(List_two)
##The output is:
Traceback (most recent call last):
  File "C:UsersAnup kumareclipse-workspaceFirstProjectPythonFirstPythonPackageFirstPythonModule.py", line 2, in <module>
    List_two=List_one*2.0
TypeError: can't multiply sequence by non-int of type 'float

repetition-error

Equality Operators for List

We can use the equality operator to compare the elements of two objects. The operators which are used to compare the list elements are

  • Equal to(==)
  • Not equal(!=)

Python Returns True when

  • The Elements of the two list must be the same.
  • The Order of elements must be the same.
  • The content of elements including the case must be the same.

Example:

List_one=['Elephant','Zebra','Tiger']
List_two=['Elephant','Zebra','Tiger']
List_three=['Dog','Cat','Sheep']
List_four=['dog','Cat','sheep']
print(List_one==List_two)
print(List_one==List_three)
print(List_two==List_three)
print(List_three==List_four)
print(List_two!=List_three)
print(List_three!=List_four)
##The output is:
True
False
False
False
True
True

Example:

List_one=['Elephant','Zebra','Tiger']
List_two=['Elephant','Zebra','Tiger']
List_three=['Dog','Cat','Sheep']
List_four=['dog','Cat','sheep']
print(List_two!=List_three)
print(List_three!=List_four)
##The output is:
True
True

Relational Operator for list

The relational operator compares the first element of the list and returns True or False depending on the condition.

The Relational operators are:

  • Less Than
  • Greater Than
  • Less Than or equal to
  • Greater Than or Equal to

Example:

List_one=[10,20,30,40]
List_two=[30,40,50]
print(List_one<List_two)
print(List_two>List_one)
print(List_one>=List_two)
print(List_two<=List_one)
##The output is:
True
True
False
False

comparing-list-elements-using-relattional-operator

Example:

List_one=['Dog','Horse','Cat']
List_two=['Sun','Moon','Star']
print(List_one>List_two)
print(List_two>List_one)
print(List_two>=List_one)
##The output is:
False
True
True

Membership Operators for List

Membership operators are used to validating the membership of a list element.

The membership operators are in, not in.

Example:

List_one=[2,3,4,5,6,7,8,9,10]
print( 5 in List_one)
print(11 in List_one)
print(12 not in List_one)
##The output is:
True
False
True

The Functions and Methods in List

A function in python is a built-in function which is available to use at any time.

The function is applicable for all kind of datatypes in python, that means these are applicable for List, Tuple, strings, etc..

The Functions are directly called and not on any objects in python and also we can pass the arguments by using the function and function returns the data as a result.

We can define the function by using the def keyword and call it by using the parenthesis

def my-function():
print("Hello")

The Output is:

We can pass the list as a parameter

def my_function(food):
  for x in food:
    print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)

list-functions-one

The List of python built-in functions are as follow:

Functions Description
Python abs() returns the absolute value of a number
Python all() returns true when all elements in iterable are true
Python any() Checks if any Element of an Iterable is True
Python ASCII() Returns String Containing Printable Representation
Python bin() converts an integer to a binary string
Python bool() Converts a Value to Boolean
Python bytearray() returns array of given byte size
Python bytes() returns an immutable bytes object
Python callable() Checks if the Object is Callable
Python Chr()
Returns a Character (a string) from an Integer
Python classmethod()
returns class method for a given function
Python compile()
Returns a Python code object
Python complex()
Creates a Complex Number
Python delattr()
Deletes Attribute From the Object
Python dict()
Creates a Dictionary
Python dir()
Tries to Return Attributes of Object
Python divmod()
Returns a Tuple of Quotient and Remainder
Python enumerate()
Returns an Enumerate Object
Python eval()
Runs Python Code Within Program
Python exec()
Executes Dynamically Created Program
Python filter() constructs iterator from elements which are true
Python float()
returns floating-point number from number, string
Python format()
returns a formatted representation of a value
Python frozenset()
returns immutable frozenset object
Python getattr()
returns value of a named attribute of an object
Python globals()
returns dictionary of the current global symbol table

A method in python is similar to the function except that it is associated with an object/classes.

A method is implicitly used for an object for which it is called.

The following table contains all the list Methods:

Methods Description
Python List append() Add Single Element to The List
Python List extend() Add Elements of a List to Another List
Python List insert() Inserts Element to The List
Python List remove() Removes Element from the List
Python List index() Returns smallest index of the element in the list
Python List count() Returns occurrences of an element in a list
Python List pop() Removes Element at Given Index
Python List reverse() Reverses a List
Python List sort() Sorts elements of a list
Python List copy() Returns Shallow Copy of a List
Python List clear() Removes all items from the List
Python any() Checks if any Element of an Iterable is True
Python all() Returns true when all elements in iterable are true
Python ASCII() Returns String Containing Printable Representation
Python bool() Converts a Value to Boolean
Python enumerate() Returns an Enumerate Object
Python filter() Constructs iterator from elements which are true
Python iter() Returns iterator for an object
Python list() The function creates a list in Python
Python len() Returns Length of an Object
Python max() Returns largest element
Python min() Returns smallest element
Python map() Applies Function and Returns a List
Python reversed() Returns reversed iterator of a sequence
Python slice() Creates a slice object specified by range()
Python sorted() Returns sorted the list from a given iterable
Python sum() Add items of an Iterable
Python zip() Returns an Iterator of Tuples

The append() method is used to add the element to the given list at the end.

The syntax for the append() method is

list.append()

Example:

List=[10,20,30]
List.append(40)
print(List)
##The output is:
[10, 20, 30, 40]

The following program is to add the elements from 1 to 100 to the list by using the append() method, which is divisible by 10.

List=[]
for x in range(1,101):
    if x%10==0:
        List.append(x)
print(List)
##The output is:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

The insert() method is used to add the element to the given list at the specified index.

The syntax for the insert() method is

list.insert(index,element)

Example:

List=[10,20,30,40,50]
List.insert(1,100)
print(List)
##The output is:
[10,100,20,30,40,50]

adding-element-by-using-insert-method-one

If the specified index is greater than the maximum index present in the list, then the element is added at the end of the list.

List=[10,20,30,40,50]
List.insert(60,100)
print(List)
##The output is:
[10, 20, 30, 40, 50, 100]

if-secified-index-greater-than-maxindex

If the specified index is less than the minimum index, then the element is added at the beginning of the list.

List=[10,20,30,40,50]
List.insert(-60,100)
print(List)
##The output is:
[100, 10, 20, 30, 40, 50]

if-specified-index-is-less-than-present-index

The extend() method is used to add all the elements to the list in the same sequence

The syntax for the extend() method is

list_one.extend(List_two)

Example:

List_one=["fruits","veggies","flower"]
List_two=["grains","fibers"]
List_one.extend(List_two)
print(List_one)
##The output is:
['fruits', 'veggies', 'flower', 'grains', 'fibers']

extend-method

The remove() method is used to remove a specified element from the list

The syntax for the remove() method is

list.remove(x)

Example:

List=[10,20,10,20,40]
List.remove(40)
print(List)
##The output is:
[10, 20, 10, 20]

remove-method

If the specified element is present multiple times, then the python will remove the first occurrence of the element.

List=[10,20,10,20,40]
List.remove(10)
print(List)
##The output is:
[20, 10, 20, 40]

removing-first-occurence-element

If the specified element is not present in the list then the remove() method will throw a value error.

The following example demonstrates the remove() method

List=[1,2,3,4,5,6]
print("Before Removal:",List)
element=int(input("Enter value to remove:"))
if element in List:
    List.remove(element)
    print("After Removal:",List)
else:
    print(element,"not available in the list")    
##The output is:
Before Removal: [1, 2, 3, 4, 5, 6]
Enter value to remove:4
After Removal: [1, 2, 3, 5, 6]

##The output is:
Before Removal: [1, 2, 3, 4, 5, 6]
Enter value to remove:7
7 not available in the list

program-to-remove-element

The following example demonstrates how to remove all the occurrences of an element present in the given list.

List=[1,1,1,1,2,2,2,3,3]
print("Before Removal:",List)
element=int(input("Enter value to remove:"))
while True:
    if element in List:
        List.remove(element)
    else:
        break
print("After Removal:",List)   
##The output is:
Before Removal: [1, 1, 1, 1, 2, 2, 2, 3, 3]
Enter value to remove:1
After Removal: [2, 2, 2, 3, 3]

removing-occurences-of-an-element

If we try to remove an element, which is not present in the list then the output is:

removing-occurences-of-an-element-one

The pop() method is used to remove an element present at the end of the list and returns the removed element.

The syntax for the pop() method is

list.pop()

Example:

List=[10,20,30,40,50,60]
List.pop()
print(List)
##The output is:
[10,20,30,40,50]

removing-element-by-using-pop-method

If we try to remove an element which is not present in the given list and if we apply pop() method to an empty list, then pop() method will throw an index error.

List=[10,20,30,40,50,60]
List.pop(70)
print(List)
##The output is:
Traceback (most recent call last):
  File "C:\Users\Anup kumar\eclipse-workspace\FirstProjectPython\FirstPythonPackage\FirstPythonModule.py", line 2, in <module>
    List.pop(70)
IndexError: pop index out of range

applaying-pop-method-to-empty-list

The pop() method can also be used to remove the specified element by using the index as an argument.

The syntax is:

list.pop(index)

Example:

List=[10,20,30,40,50]
List.pop(1)
print(List)
##The output is:
[10, 30, 40, 50]

pop-method-using-index

If we try to remove an element which is not present in the specified index, then pop() method will throw an index error.

List=[10,20,30,40,50]
List.pop(100)
print(List)
##The output is:
Traceback (most recent call last):
  File "C:\Users\Anup kumar\eclipse-workspace\FirstProjectPython\FirstPythonPackage\FirstPythonModule.py", line 2, in <module>
    List.pop(100)
IndexError: pop index out of range

The difference between remove() method and pop() method

Remove() Pop()
list.remove(x) is used to remove specified element list.pop() is used to remove and return last element and list.pop(x) is used to remove and return specified element present at specified index.
If the list is empty, then we will get a value error If the list is empty then we will get an index error
If remove() method won't remove any element then the return value is none. It returns removed element

The clear() method is used to remove all the elements present in the given list. The syntax is:

list.clear()

Example:

List=[10,20,30,40,50]
List.clear()
print(List)
##The output is:
[ ]

The reverse() method is used to reverse the order of the elements present in the given list.

The syntax for the reverse() method is:

List.reverse()

The following example demonstrates the reverse() method

List=[20,30,40,50,60]
print("Before reversing the element:", List)
List.reverse()
print("After reversing the element:", List)
##The output is:
Before reversing the element: [20, 30, 40, 50, 60]
After reversing the element: [60, 50, 40, 30, 20]

reversing-element

The sort() method is used to sort the elements present in the list according to the natural sorting process.

The syntax for the sort() method is:

List.sort()

If the elements present in the list are numbers, then the sort() method is going to sort by Ascending order.

List=[20,40,50,10,80]
List.sort()
print(List)
##The output is:
[10,20,40,50,80]

sorting-numbers

If the elements present in the list are alphabets, then the sort() method is going to sort alphabets in alphabetical order.

List=['c','z','h','t','u','i','f']
List.sort()
print(List)
##The output is:
['c', 'f', 'h', 'i', 't', 'u', 'z']

sorting-alphabets

If we want to sort the elements in the descending order we can use List.sort(reverse=True) method.

List=[12,5,0,4,8,9]
List.sort(reverse=True)
print(List)
##The output is:
[12, 9, 8, 5, 4, 0]

sorting-the-element-in-descending-order

To perform sorting of elements present in the list, the elements should be homogeneous, if the list contains heterogeneous elements then the sort() will throw an error.

List=[15,48,breed,]
List.sort()
print(List)
##The output is:
Traceback (most recent call last):
  File "C:\Users\Anup kumar\eclipse-workspace\FirstProjectPython\FirstPythonPackage\FirstPythonModule.py", line 2, in <module>
    List.sort()
TypeError: '<' not supported between instances of 'str' and 'int'

Aliasing and Cloning of list objects

The process of creating a duplicate reference variable to an existing list is called aliasing.

The syntax is:

List1=[12,13,14,15]
List2=List1
print(List1)
print(List2)
##The output is:
[12, 13, 14, 15]
[12, 13, 14, 15]
9913808
9913808

Both the list objects are pointing to the same object.

If we perform any changes to the List1, then that change will be reflecting on the List2 also

List1=[12,15,16]
List2=List1
List1[2]=20
print(List1)
print(List2)
##The output is:
[12, 15, 20]
[12, 15, 20]

The disadvantage of using aliasing method is that, if we made any changes to the list object by using one reference variable, it will be reflecting in the other reference variable also, so to overcome this problem we can use cloning() method.

Cloning is nothing but creating a new object without creating a duplicate reference variable.We can do this in two ways:

  • By using the slice operator
  • By using the copy() method
List1=[12,15,16]
List2=List1[::]##by using the slice operator
print(id(List1))
print(id(List2))
print(List1 is List2) 
##The output is:
6768080
6769240
False

List1=[12,15,16]
List2=List1.copy()##by using the copy method 
print(id(List1))
print(id(List2))
print(List1 is List2) 
##The output is:
6899152
6900312
False

If we make any changes to the List1, then it won't reflect in the List2

List1=[12,15,16]
List2=List1[::]
List1[1]=777
print("List1",List1)
print("List2",List2)
##The output is:
List1 [12, 777, 16]
List2 [12, 15, 16]
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions