Category: Lists

  • Access List Items

    Access List Items

    In Python, a list is a sequence of elements or objects, i.e. an ordered collection of objects. Similar to arrays, each element in a list corresponds to an index.

    To access the values within a list, we need to use the square brackets “[]” notation and, specify the index of the elements we want to retrieve.

    The index starts from 0 for the first element and increments by one for each subsequent element. Index of the last item in the list is always “length-1”, where “length” represents the total number of items in the list.

    In addition to this, Python provides various other ways to access list items such as slicing, negative indexing, extracting a sublist from a list etc. Let us go through this one-by-one −

    Accessing List Items with Indexing

    As discussed above to access the items in a list using indexing, just specify the index of the element with in the square brackets (“[]”) as shown below −

    mylist[4]

    Example

    Following is the basic example to access list items −

    list1 =["Rohan","Physics",21,69.75]
    list2 =[1,2,3,4,5]print("Item at 0th index in list1: ", list1[0])print("Item at index 2 in list2: ", list2[2])

    It will produce the following output −

    Item at 0th index in list1: Rohan
    Item at index 2 in list2: 3
    

    Access List Items with Negative Indexing

    Negative indexing in Python is used to access elements from the end of a list, with -1 referring to the last element, -2 to the second last, and so on.

    We can also access list items with negative indexing by using negative integers to represent positions from the end of the list.

    Example

    In the following example, we are accessing list items with negative indexing −

    list1 =["a","b","c","d"]
    list2 =[25.50,True,-55,1+2j]print("Item at 0th index in list1: ", list1[-1])print("Item at index 2 in list2: ", list2[-3])

    We get the output as shown below −

    Item at 0th index in list1: d
    Item at index 2 in list2: True
    

    Access List Items with Slice Operator

    The slice operator in Python is used to fetch one or more items from the list. We can access list items with the slice operator by specifying the range of indices we want to extract. It uses the following syntax −

    [start:stop]

    Where,

    • start is the starting index (inclusive).
    • stop is the ending index (exclusive).

    If we does not provide any indices, the slice operator defaults to starting from index 0 and stopping at the last item in the list.

    Example

    In the following example, we are retrieving sublist from index 1 to last in “list1” and index 0 to 1 in “list2”, and retrieving all elements in “list3” −

    list1 =["a","b","c","d"]
    list2 =[25.50,True,-55,1+2j]
    list3 =["Rohan","Physics",21,69.75]print("Items from index 1 to last in list1: ", list1[1:])print("Items from index 0 to 1 in list2: ", list2[:2])print("Items from index 0 to index last in list3", list3[:])

    Following is the output of the above code −

    Items from index 1 to last in list1:  ['b', 'c', 'd']
    Items from index 0 to 1 in list2:  [25.5, True]
    Items from index 0 to index last in list3 ['Rohan', 'Physics', 21, 69.75]
    

    Access Sub List from a List

    A sublist is a part of a list that consists of a consecutive sequence of elements from the original list. We can access a sublist from a list by using the slice operator with appropriate start and stop indices.

    Example

    In this example, we are fetching sublist from index “1 to 2” in “list1” and index “0 to 1” in “list2” using slice operator −

    list1 =["a","b","c","d"]
    list2 =[25.50,True,-55,1+2j]print("Items from index 1 to 2 in list1: ", list1[1:3])print("Items from index 0 to 1 in list2: ", list2[0:2])

    The output obtained is as follows −

    Items from index 1 to 2 in list1: ['b', 'c']
    Items from index 0 to 1 in list2: [25.5, True]
    
  • Lists

    Python Lists

    List is one of the built-in data types in Python. A Python list is a sequence of comma separated items, enclosed in square brackets [ ]. The items in a Python list need not be of the same data type.

    Following are some examples of Python lists −

    list1 =["Rohan","Physics",21,69.75]
    list2 =[1,2,3,4,5]
    list3 =["a","b","c","d"]
    list4 =[25.50,True,-55,1+2j]

    List is an ordered collection of items. Each item in a list has a unique position index, starting from 0.

    A list in Python is similar to an array in C, C++ or Java. However, the major difference is that in C/C++/Java, the array elements must be of same type. On the other hand, Python lists may have objects of different data types.

    A Python list is mutable. Any item from the list can be accessed using its index, and can be modified. One or more objects from the list can be removed or added. A list may have same item at more than one index positions.

    Accessing Values in Lists

    To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −

    list1 =['physics','chemistry',1997,2000];
    list2 =[1,2,3,4,5,6,7];print("list1[0]: ", list1[0])print("list2[1:5]: ", list2[1:5])

    When the above code is executed, it produces the following result −

    list1[0]:  physics
    list2[1:5]:  [2, 3, 4, 5]
    

    Updating Lists

    You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. For example −

    list=['physics','chemistry',1997,2000];print("Value available at index 2 : ")print(list[2])list[2]=2001;print("New value available at index 2 : ")print(list[2])

    When the above code is executed, it produces the following result −

    Value available at index 2 :
    1997
    New value available at index 2 :
    2001
    

    Delete List Elements

    To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. For example −

    list1 =['physics','chemistry',1997,2000];print(list1)del list1[2];print("After deleting value at index 2 : ")print(list1)

    When the above code is executed, it produces following result −

    ['physics', 'chemistry', 1997, 2000]
    After deleting value at index 2 :
    ['physics', 'chemistry', 2000]
    

    Note − remove() method is discussed in subsequent section.

    Python List Operations

    In Python, List is a sequence. Hence, we can concatenate two lists with “+” operator and concatenate multiple copies of a list with “*” operator. The membership operators “in” and “not in” work with list object.

    Python ExpressionResultsDescription
    [1, 2, 3] + [4, 5, 6][1, 2, 3, 4, 5, 6]Concatenation
    [‘Hi!’] * 4[‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]Repetition
    3 in [1, 2, 3]TrueMembership

    Indexing, Slicing, and Matrixes

    Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.

    Assuming following input −

    L = ['spam', 'Spam', 'SPAM!']
    
    Python ExpressionResultsDescription
    L[2]SPAM!Offsets start at zero
    L[-2]SpamNegative: count from the right
    L[1:][‘Spam’, ‘SPAM!’]Slicing fetches sections

    Python List Methods

    Python includes following list methods −

    Sr.No.Methods with Description
    1list.append(obj)Appends object obj to list.
    2list.clear()Clears the contents of list.
    3list.copy()Returns a copy of the list object.
    4list.count(obj)Returns count of how many times obj occurs in list
    5list.extend(seq)Appends the contents of seq to list
    6list.index(obj)Returns the lowest index in list that obj appears
    7list.insert(index, obj)Inserts object obj into list at offset index
    8list.pop(obj=list[-1])Removes and returns last object or obj from list
    9list.remove(obj)Removes object obj from list
    10list.reverse()Reverses objects of list in place
    11list.sort([func])Sorts objects of list, use compare func if given

    Built-in Functions with Lists

    Following are the built-in functions we can use with lists −

    Sr.No.Function with Description
    1cmp(list1, list2)Compares elements of both lists.
    2len(list)Gives the total length of the list.
    3max(list)Returns item from the list with max value.
    4min(list)Returns item from the list with min value.
    5list(seq)Converts a tuple into list.