0

I am trying to solve a problem and I am not able to do it. So the problem is that I have a function in Python. And I have 3 cases and I want my function to be general for all these cases. So my function needs an argument which is a array like this a = [a1, a2, a3] and for each case 2 of the elements in the array are constant and the other is variable, I explain this in more detail with this example code:

# I have my function:

def example(r,a):
    # r is an array. Inside this function I have a for loop
    for i in xrange(len(r)):
         #inside this loop is where I have the 3 cases:
         a = [r[z], a[1], a[2]]
         a = [a[0], r[z], a[2]]    
         a = [a[0], a[1], r[z]]
    (rest of the code)
     ...

so I want to find a way to declare a so my function knows where to place the variable r[z] I know that it is posible to do it with if statments but I am looking for a one-line solution, something like a way to put the variable r[z] in a given position of the array a. Or I don't know any efficient way is appreciated.

Thank you in advance.

Regards

Kilian A.G.
  • 123
  • 1
  • 6

2 Answers2

0

Use insert() to insert an element before a given position.

For instance, with

arr = ['A','B','C']
arr.insert(0,'D')
arr becomes ['D','A','B','C'] 

because 'D' is inserted before the element at index 0.

Now, for

arr = ['A','B','C']
arr.insert(4,'D')
arr becomes ['A','B','C','D']

because 'D' is inserted before the element at index 4 (which is 1 beyond the end of the array).

Original answer: Inserting values into specific locations in a list in Python

Community
  • 1
  • 1
Raskayu
  • 735
  • 7
  • 20
  • Mmm yes but this doesn't solve my problem, since how can I define the array so the function instert my variable in a given position. I mean I want to provide the function the information of where to insert the variable inside of the array. Something like: a=['inserthere',a2,a3] so the function will insert the variable in the place of 'inserthere' – Kilian A.G. Aug 16 '16 at 11:38
  • You pass that position to insert(), so I don't get your point – Raskayu Aug 16 '16 at 11:49
0

I have found I way of doing it:

 #if I define a as:

 a = [a1, True, a3]

 # I can use

 np.place(a, a==True, r[z])

In this way it will replace the value where a[i] = true by r[z]

Kilian A.G.
  • 123
  • 1
  • 6