Signup/Sign In

List Slicing in Python with Examples

Posted in Programming   LAST UPDATED: AUGUST 13, 2021

    We might have come across situations wherein we needed to access just a part of the data, or a subset of a string or a few elements of the list. This is when the concept of Data Slicing comes into picture.

    What is Data Slicing?

    Data Slicing is the process of accessing a part/subset of a given sequence of data. This technique comes in handy when we have to test some sample code or debug the code or look for logical errors, based on a huge dataset, which consumes lot of memory and takes more time to execute. In such a case we can use data slicing, to get a chunk of data from the complete dataset and use it for testing.

    We can also use data slicing, to divide a large dataset into smaller chunks for fast processing. In short, there are many use cases where smaller data sets makes the code efficient thereby saving execution time, memory and your screen time.

    In today's post, we will see slicing on one of the most widely using Python data structure - Lists.


    Alright, what is List Slicing now?

    List slicing refers to accessing a specific portion or a subset of the list for some operation while the orginal list remains unaffected. The slicing operator in python can take 3 parameters out of which 2 are optional depending on the requirement.

    Syntax of list slicing:

    list_name[start:stop:steps]

    The start parameter is a mandatory parameter, whereas the stop and steps are both optional parameters.

    The start represents the index from where the list slicing is supposed to begin. Its default value is 0, i.e. it begins from index 0.

    The stop represents the last index up to which the list slicing will go on. Its default value is (length(list)-1) or the index of last element in the list.

    The steps represents the number of steps, i.e after every n number of steps, the start index is updated and list slicing is performed on that index, or in simpler words, steps if defined, specifies the number of elements to jump over while counting from start to stop, if it is 1 then slicing will slice a subset out of the given sequence from start to stop, but if it is given value 2, then starting from start, every second character(in case of a string) or every second data element will be picked up until stop.

    This means we can do list slicing in three ways:

    1. By passing just the start or stop parameter

    2. By passing the start and stop parameter

    3. By passing the start, stop, and steps parameters

    Well, we are here for a surprise: There is a fourth way of accessing a list using colons only. Wait till you see it!


    Time for some Examples!

    Let us look at different ways in which a list can be sliced, which would lead to different results. These operations come in handy while running through a loop or traversing a data frame.

    1. Passing the start or stop index only

    my_first_list = [1,2,3, 'Studytonight', 1.23]
    
    print(my_first_list[-1]) # The index of the last element is usually the length of the data structure subtracted by 1. 
                             # This can be represented as index -1 too. Hence indexing the list with -1 displays the last element 
                             # present in the list.
    
    print(my_first_list[-3]) # On the similar lines like in previous code, the third element from the last index can be accessed 
                             # by providing the 'start' index as -3.
    
    print(my_first_list[3:]) # This indicates that the 'start' index is 3, but the 'stop' index has been left blank. 
                             # In such cases, the default value of the 'stop' index is considered. 
                             # This indicates that all the element starting from 3rd index up to the last index to be displayed.
    
    print(my_first_list[ : 4]) # Here, the 'start' index is empty, indicating its default value is to be considered while 
                               # slicing the list. The 'stop' index has been mentioned as the 4th index. 
                               # Here is the catch - the last index must be excluded. This means elements up to 3rd index 
                               # only will be displayed.

    Output:

    1.23
    3
    ['Studytonight', 1.23]
    [1,2,3, 'Studytonight']

    Follow the comments provided in the code to understand what the code is doing. In the above code, we have specifed 4 different ways of list slicing.

    2. Passing the start and stop index

    my_first_list = [1,2,3, 'Studytonight', 1.23]
    
    print(my_first_list[1 : 4]) # This indicates that the start index is 1 and the end index is 4, 
                                # but the 4th element is excluded. 
    
    print(my_first_list[-3:-1]) # It indicates that the first element to be displayed is the third element from the end. 
                                # Beginning from that index, go all the way up to the last element (-1) excluding 
                                # the last element.
    
    print(my_first_list[0:6])   # This indicates that the 'start' index is 0 and the 'stop' index is 6, 
                                # meaning beginning from the 0th index, display elements up to and 
                                # excluding the 6th index element.
    

    Output:

    [2, 3, 'Studytonight']
    [3, 'Studytonight']
    [1, 2, 3, 'Studytonight', 1.23]

    4. Passing the step parameter with colons

    my_first_list = [1,2,3, 'Studytonight', 1.23]
    
    print(my_first_list[ :: -1]) # This indicates that elements should be displayed beginning from the last index 
                                 # (notice the 2 semi-colons, instead of one). Since no value for the 'start' index has 
                                 # been specified, it takes the default value of 0 index and displays elements 
                                 # in the reverse order.
    
    print(my_first_list[ :: -2]) # Since two semi-colons are present, this indicates that the elements should be 
                                 # displayed in the reverse order, beginning from the last element. 
                                 # The -2 after the 2 semi-colons means display elements beginning from the last index 
                                 # then the second element from the end and so on(every second element). Remember to start counting from -1 index. 
                                 # Hence, the last element is displayed. Counting from the last element, 2 elements backwards 
                                 # would give 3. And two elements backwards starting from 3 would give 1.
    
    print(my_first_list[ :: 2])  # This is just the opposite of the previous code, wherein the index indicates that the 
                                 # list should be displayed from the beginning index, i.e 0. After this, count 2 elements 
                                 # ahead, beginning from 0, starting from 0th index element and move 2 indices ahead, 
                                 # which gives 3.
    
    print(my_first_list[::])     # Passing two colons to the list indicates that there is no limit on the start, stop and step 
                                 # indices. Hence, all the elements present in the list are displayed.
    
    print(my_first_list[ : ])    # This indicates no limit on the start and stop parameters, hence default values are 
                                 # considered and the entire list is displayed. 

    Output:

    [1.23, ‘Studytonight’, 3,2,1]
    [1.23, 3, 1]
    [1, 3, 1.23]
    [1, 2, 3, 'Studytonight', 1.23]
    [1, 2, 3, 'Studytonight', 1.23]

    5. Passing start, stop, and step parameters

    my_first_list = [1,2,3, 'StudyTonight', 1.23]
    
    my_first_list[0 : 3 : 1]  # The values for start index is 0, stop index is 3 and step index is 1. 
                              # This means beginning from the 0th index, display every element (since step is 1), 
                              # and go up to the 3rd index, but don't include the element at 3rd index

    Output:

    [1, 2, 3]
    
    


    Quick Fact:

    List slicing just provides a view of the subset of the original list. If you wish to change the contents of the original list by slicing or you wish to give the sliced list a new name, the sliced list has to be assigned to a new list variable.

    my_first_list = [1,2,3, 'StudyTonight', 1.23]
    # slicing list and overiding its original value
    my_first_list = my_first_list[-1]
    print(my_first_list)
    
    my_list = [1,2,3, 'StudyTonight', 1.23]
    # slicing list and storing the new sliced list in different variable
    my_second_list = my_list[-1]
    print(my_second_list)

    Output:

    1.23
    1.23

    Quick tip: Always remember to give a unique name to the list and don't call it by its generic names like list or tuple or dictionary since this will cause complications while calling functions on these data structures.

    Also read:

    Published by: SmritiSatyan
    Tags:PythonPython ListsProgrammingList Slicing
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS