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]

Tuple Datatype

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

Set Datatype

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

Dictionary Datatype

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 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 applying 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 items 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

Functions in Python

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

Introduction to Python Package

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

Python Object Oriented Programming Language

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

Python Constructor

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

Variables in Python

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 that 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/class.

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&

Methods in Python

Nested List in Python

A-List inside another List is called a Nested List.

Example:

List=[4,5,6,[8,9]]

Four elements are present in the above list, [8,9] is considered as a single element.

To access the elements of the list as

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

accessing-the-nested-list-element-python

We can access the Nested list elements as

List=[4,5,6,[8,9]]
print(List[3][0])
print(List[3][1])
##The Output is:
8
9

accessing-the-nested-list-element-python-string

Garbage Collector in Python

Representing the Nested List as Matrix

Python supports the developers in creating a matrix by using the nested list.

The following example demonstrates creating a matrix by using a nested list

List=[[10,20,30],[40,50,60],[70,80,90]]
print(List)
print("Elements row wise:")
for x in List:
    print(x)
print("Elements in Matrix style:")
for x in List :
    for y in x:
        print(y,end=' ')
    print()     
##The output is:
[[10, 20, 30], [40, 50, 60], [70, 80, 90]]
Elements row wise:
[10, 20, 30]
[40, 50, 60]
[70, 80, 90]
Elements in Matrix style:
10 20 30 
40 50 60 
70 80 90 

printing-elements-in-matrix-style

Super() Function in python

List comprehension in python

The easy and concise way of creating list objects from any iterable objects based on some conditions.

The syntax for the list comprehension is:

List=[expression for an item in list if the condition]

In the normal way, we create a list object as follow:

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

The same List we can create by using the comprehensive way as follow:

The following program demonstrates the creation of a list element with square values from 1 to 10

List=[x*x for x in range(1,11)]
print(List)
##The output is:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

The next program demonstrates the creation of list elements by considering the values from 1 to 5 to the power of 2

List=[2**x for x in range(1,6)] ## the ** is an exponential operator
print(List)
##The output is:
[2, 4, 8, 16, 32]

The following example demonstrates the creation of a list with elements which are divisible by 10

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

The next example demonstrates the creation of a list with elements present in the List1 but not in List2

List1=[10,20,30,40]
List2=[30,40,50,60]
List3=[x for x in List1 if x not in List2]
print(List3)
##The output is:
[10, 20]

The next example demonstrates the creation of a list with elements present in both List1 and List2(That means python is going to create a list with the common elements present in both the lists)

List1=[10,20,30,40]
List2=[30,40,50,60]
List3=[x for x in List1 if x in List2]
print(List3)
##The output is:
[30, 40]

The following example demonstrates the creation of a new list with the first letter of every element present in the given list.

List=['Apple','Banana','Carrot','Dragon fruit']
new_List=[word[0] for word in List]
print(new_List)
##The output is:
['A', 'B', 'C', 'D']

The following example demonstrates the creation of a new list from the given list, where every word should be in upper case and representing the number of letters present in each word in a separate list.

string="the quick brown fox jumps over the lazy dog"
words=string.split()
List=[[word.upper(),len(word)] for word in words]
print(List)
##The output is:
[['THE', 3], ['QUICK', 5], ['BROWN', 5], ['FOX', 3], ['JUMPS', 5], ['OVER', 4], ['THE', 3], ['LAZY', 4], ['DOG', 3]]

list-comprehensive-program

The following program demonstrates the display of unique vowels present in the given word

vowels=['a','e','i','o','u']
word=input("Enter any word to search for vowels:")
result=[]
for character in word:
    if character in vowels:
        if character not in result:
            result.append(character)
print(result)
print("The number of unique vowels:",len(result))           
##The output is:
Enter any word to search for vowels:orange
['o', 'a', 'e']
The number of unique vowels: 3

finding-the-vowels-in-the-word

We can shorten the above code as

vowels=['a','e','i','o','u']
word=input("Enter any word to search for vowels:")
result=[ch for ch in vowels if ch in word]
print(result)
print("The number of unique vowels:",len(result))           
##The output is:
Enter any word to search for vowels:swiss
['i']
The number of unique vowels: 1

finding-vowels-in-string

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions