160k views
5 votes
When it searches for another Cindy, why is there + 1 (-3 line of code)

friends=[]

friends.append("Harry")

friends.append("Jack")

friends.append("Mason")

friends.insert(1, "Cindy")

friends.append("Cindy")


print(friends)

print()

if "Cindy" in friends: #to check if the element is on the list

print("She is a friend")


# What if i want to know the index of Cindy? In that case do this....

print()

cindy_sIndex = friends.index("Cindy")

cindy_sIndex2 = friends.index("Cindy", cindy_sIndex + 1) # searches for other instances of Cindy

print(cindy_sIndex)

print(cindy_sIndex2)


When it searches for another Cindy, why is there + 1 (-3 line of code)

1 Answer

5 votes

Answer:

The +1 after cindy_sIndex in the line cindy_sIndex2 = friends.index("Cindy", cindy_sIndex + 1) specifies the starting position for the search for the second occurrence of "Cindy" in the list. 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", "Cindy", "Jack", "Mason", "Cindy"] and you want to find the index of both occurrences of "Cindy", 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 "Cindy"). This means that the search will start at index 2 and will find the second occurrence of "Cindy" at index 4.

Here is some example code that demonstrates how this works:

friends = ["Harry", "Cindy", "Jack", "Mason", "Cindy"]

# Find the first occurrence of "Cindy"

cindy_sIndex = friends.index("Cindy")

print(cindy_sIndex) # Output: 1

# Find the second occurrence of "Cindy"

cindy_sIndex2 = friends.index("Cindy", cindy_sIndex + 1)

print(cindy_sIndex2) # Output: 4

User Nstoitsev
by
4.5k points