-1

I am try to check if a number "n" is in list1 or list2. First, I use for loop and append it to list1 (90...110) then, I repeat it for list2 (190...210) as well. Finally, I check if a number "n" is on list1 or list2.

Disclaimer?? I just figured out you can't get lists out of for loops(can you?) so, I built the for loop and stuff it inside a pre-determined list.

Full code;

n =[89]
lst1 = []
for i in range(90,111):
   lst1.append(i)
print(lst1)
lst2 = []
for y in range(190, 211):
   lst2.append(y)
print(lst2)
if n in lst1 or lst2:
   print(f"{n} is in list1 or list 2")
else:
   print(f"{n} is NOT in list1 or list 2")

I started Python just few days ago, so don't shit on me so much pls, thx.

EDIT: juanpa.arrivillaga's comment helped me to get it working. thanks man

I changed this

if n in lst1 or lst2:
    print(f"{n} is in list1 or list 2")

to this

if (n in lst1) or (n in lst2):
    print(f"{n} is in list1 or list 2")

but it doesn't for for some reason and I can't wrap my head around it.

Deniz
  • 17
  • 5
  • your trying to search a list inside a list , nested list? – Kayes Fahim Aug 03 '22 at 05:22
  • Python, although it looks like natural language English, is not. it is a programming language, and is much more literal than you would expect. `n in lst1 or lst2` is interpreted as `(n in list1) or list2`. You want `n in list1 or n in list2` – juanpa.arrivillaga Aug 03 '22 at 05:24
  • Imagine if you had a list that contained all of the elements of `lst1` and also contained all of the elements of `lst2`. Can you think of a simple way to write code to get that list? Can you think of how that list would help you solve the problem? – Karl Knechtel Aug 03 '22 at 05:24
  • You can check directly against a range btw: `if n in range(90, 111):` – BeRT2me Aug 03 '22 at 05:24
  • also note, as others have pointed out, `n` is actually a `list`, not a number, and you don't have to create `list1` and `list2`, you can just use the `range` objects directly – juanpa.arrivillaga Aug 03 '22 at 05:25
  • No nested list, two sperate lists. like if n in list1 or list2: print(f"{n}" is in list1 or list 2) – Deniz Aug 03 '22 at 05:25
  • "I just figured out you can't get lists out of for loops(can you?)" I'm not sure what you are asking here. – juanpa.arrivillaga Aug 03 '22 at 05:32
  • I'm not sure what you are asking here. => let's say you need a list from 1 to 10 like: list = [1, 2, 3.....10] Can you get that out of a for loop without creating a empyt list and then appending x (for x in range(1,11: )to it? – Deniz Aug 03 '22 at 05:41

1 Answers1

0

It seems that boolean operation is calculated in this way.

if (n in lst1) or (lst2):

Try:

n =[89]
lst1 = []
for i in range(90,111):
   lst1.append(i)
print(lst1)
lst2 = []
for y in range(190, 211):
   lst2.append(y)
print(lst2)
if n in lst1 + lst2:
   print(f"{n} is in list1 or list 2")
else:
   print(f"{n} is NOT in list1 or list 2")
core_not_dumped
  • 759
  • 2
  • 22