504,212 views
44 votes
44 votes
What does that +1 do when checking for another Emily

What does that +1 do when checking for another Emily-example-1
User Matthew Law
by
2.6k points

1 Answer

29 votes
29 votes

Answer:

The +1 after n in the line n2 = friends.index("Emily", n + 1) tells the index method to start the search for "Emily" after the index of the previous match. This is useful if you want to find all occurrences of an element in a list and you only want to find matches that occur after the previous one.

For example, if the list is ["Harry", "Emily", "Bob", "Cari", "Emily"] and you want to find the index of both occurrences of "Emily", you can use the index method in a loop and specify a starting position for the search each time. The first time you call the index method, you start the search at the beginning of the list (at index 0). The second time you call the index method, you start the search after the index of the previous match, which is 1 (the index of the first occurrence of "Emily"). This means that the search will start at index 2 and will find the second occurrence of "Emily" at index 4.

Here is some example code that demonstrates how this works:

friends = ["Harry", "Emily", "Bob", "Cari", "Emily"]

# Find the first occurrence of "Emily"

n = friends.index("Emily")

print(n) # Output: 1

# Find the second occurrence of "Emily"

n2 = friends.index("Emily", n + 1)

print(n2) # Output: 4

User CCurtis
by
3.2k points