Python Forum

Full Version: Formula with elements of list - If-condition regarding the lists elements
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys,

I am a beginner with Python so please don´t be too harsh on me.

Currently I am working on recursive functions in general.

Please take a look at my code, which contains just a simple formula y = x1 + x2, where x1 should be an element of my list "lst1".

import numpy as np
lst1 = [1.3, 2.4, 3.7, 4.4, 5.5, 5.8]
x1 = np.array(lst1)
if x1.any() == 1.3:
    x2 = 3
else:
    x2 = 10
y = x1 + x2
print y
This simple code is for me to test out the mechanism of if-conditions which result in different values for a variable (in my case x2).

For me, it looks like the code says in line 4:

If any value of my lst1 is 1.3, then x2 = 3. So y would be printed out as 4.3 for the first element of my list.

But my code does not do that. The y for the first element is printed out as 11.3, so Python doesn´t see the if condition as given.

Why is that?

My goal is to be able to set up a bunch of if conditions, which are respected for each element one after another as Python goes trough my lists elements.

Thank you very much for your patience.

Greetings

lewie
Try this code:

if lst1.any(x1):

Actually, I just read an article on any(). It returns based on the boolean value of an item in an iterable.

Examples:
list = [0, False]
print(any(list))
This will return False because 0 and False = False.
Hope below code clarifies your doubt.
import numpy as np
lst1 = [1.3, 2.4, 3.7, 4.4, 5.5, 5.8]
x1 = np.array(lst1)
x2+3 if 1.3 in lst1 else x2+10
y = x1 + x2
print(y)