I have a couple of questions about my code solution (see below) for #4 Same Values in the above link.
def same_values(lst1, lst2):
same = []
for index in range(len(lst1)):
for index in range(len(lst2)):
if lst1[index] == lst2[index]:
same.append(index)
return same
Don’t we have to unpack both lst1 and lst2 in order to be able to loop through them both? Codecademy solution does not include my second for loop.
Can someone confirm that [index] in brackets means the value at that index position and that (index) in parenthesis means the index position number (i.e. 0 is the first in the list, 1 is the second in the list, etc …) … this is always the case?
First, let’s start by using two identifiers, not one as iteration variables.
for i in ...:
for j in ...:
This way we do not create a collision scenario that will totally mess up the outer loop.
The subscript of an iterable is given by [index], as in,
lst1[i]
lst2[j]
Last, when return is executed inside the loop, it exits the function immediately, thereby interrupting the loop. Be sure that return is not reached until all loops are completed.
To your last question, the subscript is described above, so that leaves,
y = iterable.index(x)
All iterables in Python have a built in .index() method for finding, the first occurrence of the value represented by, x. The return is either the index position of the found value, or -1 if no match found.
Note: The above method cannot be relied upon to find all occurrences in the case there are multiples (duplicates), only the first, period.
Give these thoughts a whirl and let us know how you make out.
You’re welcome. Must confess, though, the description for .index() contains an error. There is no return if the value is not found. Python raises a ValueError exception.
It’s the JavaScript equivalent, .indexOf() that returns -1. Pardon my misdirection.
This implies the need of a small workaround to prevent a fatal error in our program. Nobody likes to see exceptions raised that are not expected or intentional.
>>> a = [1, 2, 3, 4, 5, 6]
>>> k = a.index(7) if 7 in a else -1
>>> print (k)
-1
>>> k = a.index(4) if 4 in a else -1
>>> print (k)
3
>>>
When we bring up the data structure of ‘dictionary’ we learn it comes with its own .get() method for which we can provide a default when a key is not present.