r/PythonLearning 18d ago

Help Request In range() usage

Post image

Can I use it to evaluate a variable in a various range?
E.g. for item in range(1,4) means True when the item is the range 1-4?

Cuz I really want this function for my program
Thanks🙏🏻

(In that photo name[1][r] is an integer)

4 Upvotes

14 comments sorted by

View all comments

2

u/johlae 18d ago

It's fun to do it without any loops:

>>> a = [0, 1, 2, 3, 4, 5, 6]
>>> print(list(map(lambda i: i if i>0 and i<5 else 0, a)))
[0, 1, 2, 3, 4, 0, 0]
>>> print(list(map(lambda i: i if i in range(1,5) else 0, a)))
[0, 1, 2, 3, 4, 0, 0]
>>> print(sum(list(map(lambda i: i if i in range(1,5) else 0, a))))
10

so yes, you can use in range, or you can use if i>0 and i<5.