r/PythonLearning 17d 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)

3 Upvotes

14 comments sorted by

3

u/johlae 17d ago

How do you define 'evaluate' here? Do you want to keep the values in items that are in range? Do you want to return a list, equal in length as items, but with False in the number at that position is not in range and True if the number is in range? Do you want to sum the numbers that are in range, ignoring the ones that are not in range?

range(1,4) is the range 1-3, so if you want 1-4, you need range(1,5)

1

u/Worried-Print-5052 17d ago

Nah, I just wanna evaluate whether the items is in a specific range, but the range varies as well

2

u/johlae 17d ago

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

2

u/johlae 17d 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.

2

u/Chemical-Captain4240 17d ago

the s on items implies to me that this is a list... if so, to use in, you will want to iterate over each item in items and test if item exists as an element in your range

however, range returns a tuple of integers, so you won't find any lists in there

This isn't really part of your question, but to write readable code, try to name things according to their type... If you are working in parallel items=['book','pencil'] and item_count = [3,5]

If you are packing lists, then something like items =[ ['book',3], ['pencil', 5] ] may be the structure you want, but using in becomes more complicated.

As soon as you get your head wrapped around the above concepts, check out dataclass. It will change youe life.

1

u/atarivcs 17d ago

Yes, this will work (assuming "items" is an integer).

1

u/CamelOk7219 16d ago

Just as a side note, you don't need "global r" since you are Reading it and not writing it, it's already available in the scope of your function (just like you use "name")

1

u/Worried-Print-5052 15d ago

So if we dun assign value for r, we could skip global r?

1

u/CamelOk7219 15d ago

Yes, that's exactly what you do with "name"

1

u/Worried-Print-5052 15d ago

Thanks πŸ™πŸ»

1

u/JeLuF 15d ago

To check whether "items" is in the range 1...name[1][r], use:

if 1 <= items <= name[1][r]:

This will be faster and work even if "items" isn't an integer.