Reputation: 29
n = 2
list1 = [1,4,6,2,8,9,90]
How would I go about finding the number prior to the number n
stored above in list1
and store it in the variable list1_result
?
Upvotes: 2
Views: 7541
Reputation: 75
You can write a function which will scan through your list and return the desired number if found a match with n
Try this:
def find_previous(List1, n):
for i in range(len(List1)):
if List1[i] == n and i > 0:
return List1[i-1]
return None
Upvotes: 0
Reputation: 1788
You'll want to find the index of n
in the list then subtract 1 to get the position of the element before it.
n = 2
List1 = [1,4,6,2,8,9,90]
prev_elem = List1[List1.index(n) - 1]
Upvotes: 0
Reputation: 71451
You can find the index of the number in the list and then use that to find the previous element:
lst = [1,4,6,2,8,9,90]
the_index = lst.index(n)
lst2 = lst[the_index-1]
Now, you have the new list stored in lst2
Upvotes: 0
Reputation: 3196
This should work:
List1 = [1,4,6,2,8,9,90]
n = 2
ind = List1.index(n)
list1_result = List1[ind-1] # is 6
Upvotes: 3