Signup/Sign In

What are The Lists in Python?

Posted in Programming   LAST UPDATED: NOVEMBER 24, 2022

    The list in Python is a data structure used to store the collection of items that can be of various different data types. They are dynamically allocated i.e. their size can be changed during run time as well. They can contain values of the same data type as well as of different data types.

    For example:

    list_of_numbers = [34,89,73,29,0]
    random_list = ['a',"abc", 893, 902.40, ['x','y',"xy"]]

    The first list i.e. list_of_numbers is a homogeneous list i.e. all the elements of the list are of the same data type Integer.

    The second list is a heterogeneous list i.e. random_list consists of elements of different data types, a is a character, abc is a string, 893 is an integer, 902.40 is a float value, ['x','y',"xy"] is another list inside random_list.

    Defining a List

    Lists in python are created using square brackets []. Elements of the list are written between square brackets and are separated by commas.

    Let us take an example of the list of popular programming languages.

    programming_languages = ["Python", "C++", "C", "Java", "Scala", "Kotlin", "Swift"]

    Lists in python can be ordered, and changeable, and they can contain duplicate values. Indexing in lists starts from 0, i.e. the first element can be accessed at the 0th index, the second element at the 1st index, and so on. The last element is found at the (N-1)th index, where N is the total number of elements in the list.

    Ordered List

    The ordered list is the list in which elements are arranged in some defined order. New elements can only be inserted at a particular index depending on their value. An example of an ordered list is a list of names of students in a class arranged in lexicographical order (alphabetical order).

    For instance:

    class1A = ["Aashi", "Aditiya", "Avinash", "Heer", "Jay"]

    Lists in Python can carry distinct values of different data types, an example of such a list is details of a person stored in a list.

    person_poonam = ["Poonam Maharshi", 23, "Delhi public School", "9009290299", 'F', datetime.datetime(1999, 9, 29)]

    The elements full name, school's name, and phone number of the person are stored in String data type, the age is stored as int type, the gender is stored in character data type, and date of birth is stored in the datetime.

    List with duplicate values

    Lists in python can contain duplicate values i.e. one value can appear more than once.

    random = ["peacock", "hen", "ostrich", "cuckoo", "cuckoo"]

    The above list consists of duplicate values, cuckoo and appears twice.

    Access List Elements

    To access elements of the list in python, we use the index of an element to access its value. An index is the integer value that can be used as a relative position of an element respective to the other elements of the list.

    Indexing in python starts from 0 till N-1, where N is the number of elements. Let us take an example of the list of cities.

    cities = ["Indore", "Sydney", "Vietnam", "Bhopal", "Bangalore", "Seoul"]
    
    print(cities[4]);
    print(cities[1]);


    Bangalore
    Sydney

    Here, in the example above Indore is at index 0, Sydney at index 1, and so forth. Thus, at index 4 we have Bangalore i.e. the fifth element. Here N is 6, thus an index of the last element is 5.

    Negative indexing

    Python allows negative indexing in a list. It is used to traverse the list from the end. It starts from -1 to -N, where N is the number of elements in the list. -1 refers to the last element of the list and -N to the first element in the list.

    Let us take an example of the list of vehicles as follows:

    cities = ["Bus", "Train", "Car", "Airplane", "Truck", "Bike", "Ship"]
    
    print(cities[-7]);
    print(cities[-3]);


    Bus
    Truck

    In the example above, the -1 index refers to the last element of the list i.e. Ship and -7 refers to the first element i.e. Bus.

    Adding elements to the list

    We can add elements to the existing list using various methods. A list is dynamic in nature, any number of elements can be added to the list after initialization (defining an empty list, or list with values) as well.

    append() method in Python

    Elements can be added one by one to the end of the list, using the append() function. We can only add one element at a time. It takes only the value as the parameter. To add multiple elements, we use for or while loops. These elements can be of the same type as the existing elements or can be of different data types. We can add Tuples also to the list in python as Tuples are immutable (cannot be changed once created).

    Let us take an example of the list of fruits and the user wishes to add one more fruit to the end of the list. We can use the append() function to do so. Let us see the code for the same.

    fruits = ["apples", "banana", "pineapple", "grapes"]
    new_fruit = input("Enter new fruit\n")
    fruits.append(new_fruit)
    print(fruits)


    Enter new fruit
    cherry
    ['apples', 'banana', 'pineapple', 'grapes', 'cherry']

    insert() method in Python

    To insert values at a specific index in a list, we use python's insert() function. It takes two parameters, the index, and the value. The append method can only be used to add elements at the end of the list i.e. after the last element. It takes two parameters, the first one being the index at which we wish to insert and the value of the element to be inserted.

    Let us take an example of marks of a student stored in a list. Now the list has marks for only 4 subjects but there were initially 5 subjects so we are required to enter marks of the missing subject. Thus, the user enters the subject number and marks to be entered.

    No values are lost while using the insert() operation. All the values on the given index and after it is moved one index ahead.

    Note that any index beyond the size of the list will add the element at the end of the list.

    marks = [ 89, 90, 76, 79]
    print("your list of marks\n", marks)
    # index must be between 0 to 4 as size of list is 4.
    index = int(input("Enter subject number\n"))
    input_marks = int(input("Enter marks to be entered\n"))
    marks.insert(index, input_marks)
    print(marks)
    


    your list of marks
    [89, 90, 76, 79]
    Enter subject number
    2
    Enter marks to be entered
    83
    [89, 90, 83, 76, 79]

    extend() method in Python

    This function is also used to add elements at the end of the list. It is different from the other two functions because we can add multiple elements using the extend() method. It takes a list as a parameter and adds the elements of the second list at the end of the first list.

    Let's take an example of steps associated with taking admission in an engineering college. The list steps contain pre-steps and the list additional_steps contain all the other steps. To get the complete process, we are merging additional_steps with steps using extend method in python.

    # How to become an engineer
    steps = ["Be sure of your decision", "Choose Maths and Physics subjects in your 11th and 12th", "Choose engineering field"]
    additional_steps = ["select college", "prepare for entrance the college validates", "try to score the minimum cut-off of the college", "apply for the college and relevant other colleges"]
    steps.extend(additional_steps)
    print(steps)


    ['Be sure of your decision', 'Choose Maths and Physics subjects in your 11th and 12th', 'Choose engineering field', 'select college', 'prepare for entrance the college validates', 'try to score the minimum cut-off of the college', 'apply for the college and relevant other colleges']

    Slicing of a list

    In python to access or print a particular part of the list, we use the Slice operation. The colon : is called the slice operator. The syntax of the slice operation is as follows:
    list = parent_list[starting_index : ending_index]

    Here parent_list is the list we are accessing and part of it is added to the list. starting_index and ending_index both are optional. When both are not mentioned the whole list is returned. If starting_index is not entered the list begins from the start and ends at the index mentioned. If the ending_index is not mentioned, then starting from the provided index, the list goes till the end. The ending_index is not included in the resultant index.

    Let us see examples of slicing operation

    list = ['s','t','u','d','y','t','o','n','i','g','h','t']
    print(list[:])
    print(list[:5])
    print(list[5:])
    print(list[1:10])


    ['s', 't', 'u', 'd', 'y', 't', 'o', 'n', 'i', 'g', 'h', 't']
    ['s', 't', 'u', 'd', 'y']
    ['t', 'o', 'n', 'i', 'g', 'h', 't']
    ['t', 'u', 'd', 'y', 't', 'o', 'n', 'i', 'g']

    [:] - prints the entire list

    [:5] - prints from 0th to 4th index

    [5:] - prints from 5th index till the end of the list

    [1:10] - starts from the first index and extends till the 9th index.

    Note that the ending index is not part of the resultant list.

    List Comprehension

    List Comprehension is a concise way to define a list in python. This method of creating the list is used to make new lists where each element is the result of some operations applied to the same list or another list, or some iterable. To create such lists we use an operation that loops very similar to the mathematical statements in one line only.

    It consists of four parts, output expression, input list, a variable representing a member of the input list, and operational predicate part.

    For example:

    def isPrime(num):
        if num > 1:
           for i in range(2, num):
               if (num % i) == 0:
                   return False
           else:
               return True
        
    
    prime_nos = [x for x in range (1, 21)   if  isPrime(x)]
    print(prime_nos)


    [2, 3, 5, 7, 11, 13, 17, 19]

    In the example above:

    x is the output expression i.e. it should be added to the list,

    for x in range(1,21) is input list

    x is a variable and

    if(isPrime(x)) is optional predicate i.e. if this condition is satisfied by the x then only it will be added to the list.

    In the above example, x starts from 1 and is incremented to 20. If x is prime (Checked by isPrime() function), then it is added to the list else discarded.

    Other Important List Operations

    Size of the list

    The len() function returns the size of the list, i.e. number of elements present in the list.

    list = ["Laptop", "Computers", "Personal Computers"]
    print("Length of list is - ",len(list))
    list.append("Calculators")
    print("Length of list after adding an element to it is - ",len(list))


    Length of list is - 3
    Length of list after adding an element to it is - 4

    In the example above, initially length of the list, i.e. number of items in the list was 3. After adding an item to the list the length now becomes 4.

    Check if the item exists and its count

    A built-in method count() in python returns the count of the appearance of the given element in the given list. It takes an element as a parameter and returns the number of times the given element occurs in the list. If the element exists in the list, it returns a positive integer.

    list = [3011, 2022, 3033, 4044, 5055, 2022]
    print("Count of item 2022 - ",list.count(2022))
    list.append(4044)
    print("Count of item 4048 - ",list.count(4048))


    Count of item 2022 - 2
    Count of item 4048 - 0

    The above example demonstrates the use of the count function. It returns the count of the given item in the list. If the item doesn't exists it returns zero. Thus, it can also be used to check if some item is present in the list or not.

    Join Operation

    Two lists can be joined together using the extended method discussed above. They can also be joined using the (+) plus operator.

    For example:

    list1 = ["Gujarat", "Bangalore", "Tamil Nadu", "Madhya Pradesh"]
    list2 = ["Goa", "Rajasthan", "Uttarakhand", "Sikkim"]
    list3 = list1+list2;
    print(list3)


    ['Gujarat', 'Bangalore', 'Tamil Nadu', 'Madhya Pradesh', 'Goa', 'Rajasthan', 'Uttarakhand', 'Sikkim']

    Thus, the resultant list consists of all the elements of both lists. Lists can be added just like strings or integer values using the plus (+) operator.

    Updating existing list items

    In python lists, we can update the value at a particular index using square brackets ([]).

    We can also update multiple values together using Slicing Operation i.e. [starting_index : ending_index].

    list1 = ["German", "English", "Japanese", "Hindi", "Spanish"]
    print("List before updating\n",list1)
    list1[1] = "English UK"
    list1[2:4] = ["French", "Korean"]
    print("List after updating values\n",list1)


    List before updating
    ['German', 'English', 'Japanese', 'Hindi', 'Spanish']
    List after updating values
    ['German', 'English UK', 'French', 'Korean', 'Spanish']

    In the example above list1[1] updates only the element at the first index, and list1[2:4] updates elements at the 2nd and the 3rd index.

    Deleting list elements

    The remove() method of the list in python deleted a given value from the list.

    The pop() is used to delete the element at a given position or to remove the last element of the list.

    We can also use the del keyword to delete elements at the given index.

    list1 = [x for x in range(0,20) if(x%2==0)]
    print("List initially\n",list1)
    # remove method
    list1.remove(4)
    print("List after removing 4\n",list1)
    # Removing last element using pop function
    list1.pop()
    # removing element at 0th index using pop() function
    list1.pop(0)
    print("List after removing elements using pop method\n",list1)
    # removing elements using del keyword
    del list1[4]
    print("List after deleting element at 4th index\n",list1)


    List initially
    [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
    List after removing 4
    [0, 2, 6, 8, 10, 12, 14, 16, 18]
    List after removing elements using pop method
    [2, 6, 8, 10, 12, 14, 16]
    List after deleting element at 4th index
    [2, 6, 8, 10, 14, 16]

    Sorting list

    To sort the items in the list sort() function is used. It arranges the items in the list in ascending order.

    squares = [4, 81, 64, 100, 16, 9, 25]
    print("List before sorting\n",squares)
    squares.sort()
    print("List after sorting\n",squares)


    List before sorting
    [4, 81, 64, 100, 16, 9, 25]
    List after sorting
    [4, 9, 16, 25, 64, 81, 100]

    Reversing lists

    The reverse() function in python reverses the order of the items in the list. Let us see an example of the reverse() function.

    squares = [4, 81, 64, 100, 16, 9, 25]
    print("List initially\n",squares)
    squares.reverse()
    print("List after refersing\n",squares)


    List before sorting
    [4, 81, 64, 100, 16, 9, 25]
    List after sorting
    [25, 9, 16, 100, 64, 81, 4]

    Copying List

    Coping a list using (=) operator like list1 = list2 simply passes the reference of list1 to list2. This implies that any changes made to list2 will reflect in the list1 and vice verse. To avoid this we can use the inbuilt method of python list2 = list1.copy() which copies each element of list1 to list2 rather than just passing reference. Thus, both lists are independent of each other.

    fabonacci = [0, 1, 1, 2, 3, 5, 8, 13]
    print("Fabonacci series initially\n",fabonacci)
    temp_list = fabonacci.copy()
    print("temp_list:\n",temp_list)


    Fibonacci series initially
    [0, 1, 1, 2, 3, 5, 8, 13]
    temp_list
    [0, 1, 1, 2, 3, 5, 8, 13]

    Finding index of given element

    The index() function in python returns the index of the first matching element in the given list.

    fabonacci = [0, 1, 1, 2, 3, 5, 8, 13]
    print("Fabonacci series\n",fabonacci)
    index_8 = fabonacci.index(8)
    print("index of element 8 is - ",index_8)


    Fibonacci series initially
    [0, 1, 1, 2, 3, 5, 8, 13]
    index of element 8 is - 6

    Iterating through the list

    There are various ways of traversing the list in python. We can use for loop, while loop, using list comprehension, and indices to traverse a list.

    ?
    list = ["James", "Jake", "Rosa", "Joe", "Daniel"]
    # Using for loop
    print("-> Using for loop")
    for i in list:
        print(i,end=", ")
        
    print("\n->Using while loop")
    # USing while loop
    n = len(list)
    i=0
    while(i<n):
        print(list[i],end=", ")
        i+=1
    
    print("\n->Using list comprehension")
    # using list comprehension
    [print(x,end=", ") for x in list ]
    
    print("\n->Using indices")
    # using indices
    for i in range(0,n):
        print(list[i],end=", ")
        
    
    ?

    -> Using for loop
    James, Jake, Rosa, Joe, Daniel,
    ->Using while loop
    James, Jake, Rosa, Joe, Daniel,
    ->Using list comprehension
    James, Jake, Rosa, Joe, Daniel,
    ->Using indices
    James, Jake, Rosa, Joe, Daniel,

    You May Also Like:

    About the author:
    Niyati Thakkar is a very good writer and an expert at writing about programming languages like Python and Data Structure in a technical way. Niyati has a background in Computer Science, so she has a deep understanding of these complicated topics.
    Tags:list-operationlistpython
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS