Position of an element in an array [duplicate] - python

This question already has answers here:
Searching a sorted list? [closed]
(3 answers)
Closed 4 years ago.
I need to find the position of an index based on the existence of an value in a numerical array. I understand that I can use the .index(value) method for list but the thing is I don't want the code to exit or given None or any other type of exception if the value is not present in the array. Instead I would like to know the adjacent array indices values if the exact value is not present in the list. Hope the below example makes the problem statement clear.
arr = [10,20,30,40,50]
Input: 25
Output: 1,2
Input: 20
Output: 1
Basically the code returns the indices of the adjacent values in the array within which the search input is looked for.

For a non-numpy method, you can append your input variable to your list, sort it, and find the index where your input is found in the new list, and return that as well as the previous index:
arr = [10,20,30,40,50]
i = 25
i_index = sorted(arr+[i]).index(i)
>>> [i_index-1, i_index]
[1, 2]
Edit Based on your comment: if the value is already present in the array then I need just the exact index position of that value else I need the adjacent index values within which the value is falling into
You can wrap it in an if statement to check if your input is in your array already:
if i in arr:
idx = sorted(arr).index(i)
else:
i_index = sorted(arr+[i]).index(i)
idx = [i_index-1, i_index]
>>> idx
[1, 2]

Related

Find the "best" item of a list and print the index position of the first instance in python [duplicate]

This question already has answers here:
Getting the index of the returned max or min item using max()/min() on a list
(23 answers)
Closed 4 years ago.
I need to print out the index position of the highest value of a list on its first instance.
What I have at the moment:
temperatures = [4.7, 3, 4.8, -1, 4.8, 4]
# set best_index to 0
best_index = 0
# for each position from 1 to length of list:
for position in range(0, len(temperatures)):
if position > best_index:
best_index = position
# print best_position
print(temperatures[best_position])
However, with the above code I don't get what I am looking for, as with that example list I'd get the result of 4 and not 2 as it should be.
What am I doing horribly wrong?
You're doing a few things wrong. First, you are checking if the new index is larger than the previous index, you're not checking the actual values. Second, you're printing out the actual value at the index rather than the index itself.

Hierarchical Searching in a List in Python [duplicate]

This question already has an answer here:
Recursive code returns None [duplicate]
(1 answer)
Closed 6 years ago.
I want to search a Specific Value (an Integer) in a List in Python where the List could possibly have a Hierarchical Structure, So there could be a List on a Specific index (e.g [1,2,[[3,4],[5,6]] here the index 2 is a list it self and there could be a list in that again), and So on, or the index of Original List could have Integer values itself (e.g [1,2,3,[4,5]] in this case index 0 is an integer..
Eventually, I want the index of the searched value w.r.t original List , otherwise if searched value is not in the list, it should give me -1...I'm using recursion for that, but i'm not having the desired results...
Here's My Code
def search_in_list(L,c1):
index=-1
for i in range(len(L)):
if type(L[i])==list:
search_in_list(L[i],c1)
elif type(L[i])!=list:
if c1==L[i]:
index=i
return index
and here's an example List [1,2,[[3,4],[5,6]] So let's say i want to search 6, then it should give me 2 because that's the index of original list on which 6 is present, but i'm having -1 instead...
Can someone dig into my code and tell me the problem and solution...
Thanks in Advance
You can make some modifications to work correctly:
def search_in_list(l, needle):
for i, item in enumerate(l):
if type(item) == list:
# We found it, return current index
if search_in_list(item, needle) >= 0:
return i
else:
if needle == item:
return i
return -1
The main reason it didn't work was in the recursive call. When it returned that the item was found (by returning a non negative index) you didn't return the current index.

Changing list while iterating [duplicate]

This question already has answers here:
Modifying a list while iterating over it - why not? [duplicate]
(4 answers)
Closed 6 years ago.
I've found a python puzzle and can't find out why it works.
x = ['a','b','c']
for m in x:
x.remove(m)
and after this loop x = ['b'].
But why?
As far as I understand for keyword implicitly creates iterator for this list. Does .remove() calls __next__() method so b is skipped? I can't find any mentions of it but this is my best guess.
Here you are iterating over the original list. On the first iteration, you removed the 0th index element i.e. a. Now, your list is as: ['b','c']. On the second iteration your for loop will access the value at index 1 but your index 1 has value c. So the c is removed. Hence resultant list will be ['b'].
In order to make it behave expectedly, iterate over the copy of the list, and remove the item from original list. For example:
x = ['a','b','c']
for m in list(x): # <-- Here 'list(x)' will create the copy of list 'x'
# for will iterate over the copy
x.remove(m)
# updated value of 'x' will be: []
Note: If it is not for demo purpose and you are using this code for emptying the list, efficient way of emptying the list will be:
del x[:]

Beginner Python: Deleting elements from a list [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 7 years ago.
I am working of Project Euler problem 2. I need to find the sum of all even Fibonacci numbers up to four million. I have a function that generates all possible Fibonacci numbers up to upperBound which is input by the user. I am passing this list of fibs to another function in order to eliminate the odd values. I am trying to iterate through the list and delete the element if it is odd. It is returning an error saying :
in evenFibs
del list_of_fibs[value]
IndexError: list assignment index out of range
Here is my code for evenFibs() :
def evenFibs(upperBound):
list_of_fibs = getFibs(upperBound)
for value in list_of_fibs:
if value % 2 != 0:
del list_of_fibs[value]
return list_of_fibs
I am not sure why this error is occuring.
Take a note that you shouldn't change array while iterating it, also to delete element from array you should use index of element, not value. You can get index of first element with specific value using index method of list. As for your task, it would be better to use list comprehension:
def evenFibs(upperBound):
list_of_fibs = getFibs(upperBound)
return [value for value in list_of_fibs if value % 2 == 0]

How to get the last number from list in python [duplicate]

This question already has answers here:
How do I get the last element of a list?
(25 answers)
Closed 8 years ago.
Suppose I have the list as
a = [0.0021, 0.12, 0.1224, 0.22]
I have to extract the last number from the above list, so my answer should be 0.22 without using a[3], because the number of the elements in the list always keep changing.
You're talking about a list. Arrays in python are usually numpy.arrays. They are a completely different data structure.
You can achieve what you want like this:
>>> array = [0.0021, 0.12, 0.1224, 0.22]
>>> array[-1]
0.22
>>>
Negative indexing starts at the end of the list, thus array[-1] will always be the last element in the list, array[-2] the second last and so forth.
The appropriate name of [...] is a list. As you know, you can access to an element of a list using an index, like
some_list = [1, 2, 3]
print some_list[0] # first element
But you can also use negative indices:
print some_list[-1] # last element: 3
print some_list[-2] # one before the last element: 2
Note that this will "count" elements from right to left
Don't worry! Try them!
a[len(a)-1]
or
a[-1]

Categories