Lists or arrays in Python

Lists or arrays in Python

Lists are like arrays, declared in other programming languages. Lists don't always have to be homogeneous, which makes them an extremely powerful tool in Python.

A single list can contain different types such as integers, strings, and objects.

Lists are also very useful for implementing stacks and queues. The lists are modifiable and can therefore be modified even after their creation.

In Python, list is a container type, used to store multiple data at the same time.
The elements of a list are indexed according to a defined sequence and the indexing of a list is done with 0 as the first index. Each item in the list has its defined place in the list, each item having its own location and credibility.

Creating a list

Lists in Python can be created by simply placing the sequence in square brackets [].
A list can contain duplicate values with their distinct positions. Therefore, multiple distinct or duplicate values can be passed as a sequence when the list is created.

Example 1 :
    # Empty list
    list = [] 

    # List with elements in it
    list=['lundi','mardi']

    # List with elements of different types
    list=['mostafa','essaddouki', 31, 2019]

    # List of integers
    list=[1, 2, 3]

    # List of ten elements containing only zeros
    list=[0] * 10


    # display list items

    # all the elements
    print(list)

    # first element
    print(list[0])

    # 2nd element
    print(list[1])

    # last element
    print(list[-1])

Add items

Items can be added to the list using the append() function. Only one item at a time can be added to the list using the append () method.

To add multiple elements using the append() method, loops are used. You can also add tuples to the list using append(tuple) because the tuples are immutable.

Unlike sets, lists can also be added to the existing list using the append() method. The append() method works only for adding items to the end of the list.

To add an element at the desired position, the insert() method is used. Unlike append () which takes a single argument, the insert () method requires two arguments (position, value).

In addition to the append() and insert() methods, there is an additional method for adding elements, extend(). This method makes it possible to add several elements simultaneously to the end of the list.

Example 2 :
    # Create a list
    list = []
    # Add elements to list
    list.append(1) 
    list.append(2) 
    list.append(4) 

    print("\n List after adding three items ") 
    print(list) 
    
    # add several elements (1, 2, 3) with loop
    for i in range(1, 4): 
        list.append(i)
    
    # Adding Tuples to the List 
    list.append((5, 6)) 
    print("\nList after adding a Tuple : ") 
    print(list) 
    # [1, 2, 4, (5,6)]

    # Adding a list to the List 
    list.append([3, 2]) 
    print("\nList after adding a list : ") 
    print(list)
    # [1, 2, 4, (5,6), [3,2]]

    # add an element in a specific position
    list.insert(0, 12) 
    # [12, 1, 2, 4]

    # add an element in a specific position
    list.insert(2, 12) 
    # [1, 2, 12, 4]

    # add multiple items to the end of the list
    List.extend([13 , 7, 9]) 
    
    # [1, 2, 4, 13, 7, 9]

Access the items in the list

In order to access the items in the list, we use the index number. Use the index operator [] to access an item in a list. The index must be an integer.
You access a nested list using nested indexing.

Example 3 :
    # Create a list
    List = [9, 5, 13]


    # First element
    print(list[0])
    # -> 9

    # 2nd element
    print(list[1])
    # -> 5

    # Last element
    print(list[-1]) 
    # -> 13

    # the element before the last
    print(list[-2])
    # -> 5
    
    # nested list (matrix) or 2D array
    # 3 rows et 4 columns
    # 1 , 2, 5, 7
    # 3, 7, 9, 8
    # 10, 0, 4, 19

    list=[[1, 2, 5, 7],[3, 7, 9, 8],[10, 0, 4, 19]]

    # display the element of row 2, 3rd column
    print(list[1][2])
    # -> 9

    # display the element of row 3, 2nd column
    print(list[2][1])
    # -> 0

Remove items from the list

Items can be removed from the list using the remove() function, but an error occurs if the item does not exist in the list.
The Remove() method removes only one element at a time, to remove a range of elements, a loop is used.

The Pop() function can also be used to remove and return an item from the list, but by default, it removes only the last item from the list, to remove an item from a specific position in the list, the index of the element is passed as an argument to the pop (index) method.

Notes ! The remove() method will only remove the first occurrence of the element sought.
Example 4 :
    list = [5, 7, 8, 12]
    # Remove items from the list
    list.remove(5) 
    list.remove(8) 
    print("\nList after deletion: : ") 
    print(list)
    # -> [7, 12]


    # Delete multiple items
    for i in range(3): 
        list.remove(list[i]) 
    print("\nList after deletion:: ") 
    print(list) 
    # -> [12]

    # delete last item
    list.pop() 
    print(List) 
    # [5, 7, 8, 12]

    # delete item from position 1
    list.pop(1) 
    print(List) 
    # [5, 8, 12]

Access to a range of elements (cutting or slice)

To access the elements of a specific range of the list, we use the split operation.

The splitting operation is performed on the lists using a colon (:).

  •  To access the elements at the beginning of the range, use [:Index],
  •  To access the end elements ([: -Index]),
  •  To access the elements of a specific index until the end [Index:],
  •  To access the elements of a range, use [Start index: end index] and
  •  To access the entire list using a split operation, use [:]
  •  Also, to access the entire list in reverse order, use [:: - 1].
Example 5 :
    list = [5, 7, 8, 12, 25, 18, 30]

    # display the first 3 elements
    print(list[:3])
    # -> [5, 7, 8]

    # display the elements of the list without the last 3 elements
    print(list[:-3])
    # -> [5, 7, 8, 12]

    # display the elements of position 3 until the end
    print(list[2:])
    # -> [8, 12, 25, 18, 30]

    # display items in steps of 2
    print(list[::2])
    # -> [5, 8, 25, 30]

    # display items in reverse order
    list[::-1]
    # -> [30, 18, 25, 12, 8, 7, 5]

Other Methods

sum()

Calculates the sum of all the elements in the list.

            # syntax : sum(List)
            List = [1, 6, 3, 9] 
            print(sum(List)) 
        
count()

Calculates the number of occurrences of a given item in the list.

            # syntax : List.count(value)
            List = [10, 2, 3, 9, 2, 1, 2, 3, 2] 
            print(List.count(3)) 
            # -> 2
        
length()

Calculate the size of the list

            # syntax : len(liste)
            List = [10, 2, 3, 9, 2, 1, 2, 3, 2] 
            print(len(List)) 
            # -> 9
        
index()

Returns the index of first occurrence. The start and end indexes are not necessary parameters.

            #syntax : List.index(value[,start[,end]])
            List = [10, 2, 3, 9, 2, 1, 2, 3, 2]
            print(List.index(2))
            # -> 1

            print(List.index(2,2)) 
            # -> 4

            # rechercher dans la plage 2 - 6
            print(List.index(2,2,7)) 
            # -> 4
        
min()

Calculates the minimum of all items in the list.

            # syntax min(List)
            List = [10, 2, 3, 9, 2, 1, 2, 3, 2]
            print(min(List))
            # -> 1
        
max()

Calculates the maximum of all items in the list.

            # syntax max(List)
            List = [10, 2, 3, 9, 2, 1, 2, 3, 2]
            print(max(List))
            # -> 10
        
reverse()

Reverse the order of items in the list

            # syntax List.reverse()
            List = [10, 2, 3, 9, 2, 1, 2, 3, 2]
            List.reverse()
            print(List)
            # [2, 3, 2, 1, 2, 9, 3, 2, 10]
        
sort()

Sort(tuple and list) in ascending order.
Key and reverse_flag are not necessary parameters and reverse_flag is set to False, if nothing is passed by sort().

            # Syntax of sorted : sorted([list[,key[,Reverse_Flag]]])
            # syntax of sort : list.sort([key,[Reverse_flag]])

            List = [10, 2, 3, 9, 2, 1, 2, 3, 2]
            List.sort(reverse=True)
            # -> [10, 9, 3, 3, 2, 2, 2, 2, 1]


            sorted(List)
            # -> [1, 2, 2, 2, 2, 3, 3, 9, 10]
        
del()

delete an item mentioned using the list name and its index

            # syntax del list[index]
            List = [10, 2, 3, 9, 2, 1, 2, 3, 2]
            del List[2]
            # -> List = [10, 2, 9, 2, 1, 2, 3, 2]

            # delete a range
            del List[1:3]
            # -> [10, 9, 2, 1, 2, 3, 2]

        
Operator "in"

This operator is used to check whether an element is present or not in the list. Returns true if the element is present in the list, otherwise returns false.

            List = [10, 2, 3, 9, 2, 1, 2, 3, 2]
            if 9 in List:
                print("element is present in the list")
            else:
                print("the element is not present in the list")
        
Operator "not in"

This operator is used to check if an element is not present in the list. Returns true if the element is not present in the list, otherwise returns false.

                List = [10, 2, 3, 9, 2, 1, 2, 3, 2]
                if 9 not in List:
                    print("the element is not present in the list")
                else:
                    print("element is present in the list")
            
Operator "+" et "*"

"+" : This operator is used to concatenate two lists into a single list.

"*" : This operator is used to repeat the list "n" times and return a single list.

            L1 = [1, 2, 3]
            L2 = [4, 5, 6]

            List1=L1+L2
            # -> [1,2, 3, 4, 5, 6]

            List2=L1 * 3
            # [1, 2, 3, 1, 2, 3, 1, 2, 3]
        
clear()

This function allows you to delete all items from the list. After this operation, the list becomes empty.

            List = [10, 2, 3, 9, 2, 1, 2, 3, 2]
            List.clear()
            print(List)
            # []
        

Share this course with your friends :

 
This course is written by M. ESSADDOUKI Mostafa

Many people realize their hearts desires late in life. Continue learning, never stop striving and keep your curiosity sharp, and you will never become too old to appreciate life.

0 Comment(s)

To leave a comment you must have an account Sign up, or Sign in