Category: Basic Python

  • Loops in Python: For Loop

    Loops are used when one wants to repeat a set of commands several times (iterations). For example,when you want to apply a set of operations on elements of a list, by choosing one element at a time, you can use a python loop.

    There are two types of loops:

    • For loop
    • While loop

    For loop: 

    For loop is used when we want to run the set of commands for a known or defined number of times. Few of the ways in which we can use the “for loop” is as follows:

    Python
    for i in range(10):
        print(i)
    range(start, stop, step)

    Here the range(10) function will create number in sequence starting from 0 and ending at 9. The value of i will thus stat from 0 and increase by 1 in each iteration stopping at 9

    The general format of range function is:

    Python
    range(start, stop, step)

    By default the value of step is 1. 

    The other way of running for loop is:

    Python
    mylist = ["a", "b", "c"]
    for i in mylist:
        print(i)
        
    mylist = ["a", "b", "c"]
    for i, element in enumerate(mylist):
        print(f'index: {i}, element: {element}')
    a
    b
    c

    Here, the for loop iterates over each element in the list (mylist). In the first loop the value of “i” is “a”; in the second loop the “i” has the value of “b”; and so on.

    The enumerate function allows us to simultaneously iterate over the elements of a list as well as yielding the indices of the current element in the list in a particular iteration.

    Python
    mylist = ["a", "b", "c"]
    for i, element in enumerate(mylist):
        print(f'index: {i}, element: {element}')
    index: 0, element: a
    index: 1, element: b
    index: 2, element: c

    This is useful when you might need to access the elements of other lists relative to this index in the loop.

  • List in Python

    Lists in python are collection of objects. They can include any python objects such as numerals, strings, other lists and dictionaries. The list is defined by square bracket as follows:

    Python
    my_list = []

    The above example shows an empty list. Following is an example of a list with numbers:

    Python
    my_list = [1,2,4,65,43]
    my_list
    my_list = [1,2,4,65,43]
    my_list

    Lists can also contain strings.

    Python
    list_of_str = ['abc', 'goku', 'vada_pav', 'chicken_rice']
    list_of_str
    ['abc', 'goku', 'vada_pav', 'chicken_rice']

    Single list can also contain different types of objects. Following is an example of a list containing number, string, another list and a dictionary.

    Python
    list_mix = [3, 4, 'burger', ['Chicago', 23, 'Nile'], {'city_names': ['Delhi', 'London'], 'food_items': ['idli', 'mala-hotpot', 'rojak']}]
    list_mix
    [3,
     4,
     'burger',
     ['Chicago', 23, 'Nile'],
     {'city_names': ['Delhi', 'London'],
      'food_items': ['idli', 'mala-hotpot', 'rojak']}]

    When the command lines become too long we can break the line after a comma in the list.

    Python
    list_mix = [3,
                4,
                'burger',
                ['Chicago', 23, 'Nile'],
                {'city_names': ['Delhi', 'London'],
                 'food_items': ['idli', 'mala-hotpot', 'rojak']}]
    list_mix
    [3,
     4,
     'burger',
     ['Chicago', 23, 'Nile'],
     {'city_names': ['Delhi', 'London'],
      'food_items': ['idli', 'mala-hotpot', 'rojak']}]

    List indexing

    List index starts with zero as all indexes in python. Following is the general format of indexing a list.

    my_list[from_index:to_index:step]

    The to_index is not inclusive. It means that the list item at to_index will not be included in the result of indexing. We will see this an example of a list of number from 0 to 20.

    Python
    a = list(range(20))
    a
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
     
    Python
    a[2:18:3]
    [2, 5, 8, 11, 14, 17]

    Here, we indexed the list from 2nd index to the 18th index with a step size of 3. The default stepsize is 1.

    We will see different ways of indexing/slicing a list not.

    From a defined index (e.g. 5) to end of the list.

    Python
    a[5::]
    [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

    From start of the list to a defined index (e.g. 15) including the item at that index.

    Python
    a[:15+1]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
    Python
    a[:16]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

    The last element of a list can be indexed as -1, and the second last element is indexed as -2 and so on. Following are few example to index a list using negative numbers.

    Python
    a[-1]
    19
    Python
    a[-10:-1]
    [10, 11, 12, 13, 14, 15, 16, 17, 18]

Privacy Overview
Analytics Notes

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.

3rd Party Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.