Configuration

Night mode

Advanced Functions 2

Learn Python Essentials for Data Science Course

Engineers From These Top Companies and Universities Trust EXLskills

1M+ Professionals | 100+ Institutions

This is the EXLskills free and open-source Python Introduction Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Python, to a moderate level of essential coding proficiency.

Is this course FREE?

Yes, this a 100% free course that you can contribute to on GitHub here!

As well, I am going to introduce a python built in function that is called enumerate which is super useful in for loops.

Actual Definition:

Enumerate is a built-in function of Python. It’s usefulness can not be summarized in a single line. Yet most of the newcomers and even some advanced programmers are unaware of it. It allows us to loop over something and have an automatic counter. Here is an example:

Back to index_equals

Now you may be beginning to see where I am going with this. Using the Enumerate function we can see if the value in our list is the same as the index!

Steps to a solution:

Create a function that takes in a list and returns a list

Interate through the list and check to see if the value equals the index

If the value meets our conditions add it to a new list

Return the new list

Solution TEST

def index_equals(lst):
'''
INPUT: lst = list of integers
OUTPUT: new_list = list of integers from the original list if the value matches the index
'''
# Create the new list that we are going to return
new_list = []
# Iterate through the original list and enumerate the items in it
for i,value in enumerate(lst):
# Create our logic statement to check our condition
if i == value:
# If it meets the conditions, append it to the new list
new_list.append(value)
# Return the new list
return new_list
# Test it out
list_1 = [0,1,3,4,6]
print(index_equals(list_1)) # should return [0,1]
list_2 = [1,1,2,3,6]
print(index_equals(list_2)) # should return [1,2,3]