Search code examples
pythonpython-3.xlistsublist

Comparing elements of a list with those of sublists python


I'm trying to write a function which would take a value from a list, and then see if it's in the range of two values in a sub-list. Hopefully my code will explain it better:

list1 = [1, 2, 3, 4, 5]
list2 = [[1, 3], [2, 4]]
answer = []
c = 0
for elem in list1:
    if list2[c] <= int(elem) <= list2[c+1]:
        answer.append(elem) 
        sys.stdout.write(str(answer) + ' ')
        c += 1


Expected Output: 
1 2 3
2 3 4

So what I'm trying to do is see if the value of the element in list1 is in the range of each sub-list in list2, of course the values are added to a list and then printed out. I get the error message:

Traceback (most recent call last):
  File "Task11.py", line 54, in <module>
    main()
  File "Task11.py", line 51, in main
    input_string()
  File "Task11.py", line 48, in input_string
    list_interval(input_list, query_values)
  File "Task11.py", line 16, in list_interval
    if int(list2[c]) <= int(elem) <= int(list2[c+1]):
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

Which I undestand, but I'm unsure of how to actually use the sublists in the way I mentioned.


Solution

  • Use a list-comprehension that finds all elements from list1 in the range parameters specified in list2:

    list1 = [1, 2, 3, 4, 5]
    list2 = [[1, 3], [2, 4]]
    
    lst = [[c for c in list1 if c in range(x, y+1)] for x, y in list2]
    
    print(lst)
    # [[1, 2, 3], [2, 3, 4]]

    The range() helps to create a range of numbers starting from its first parameter excluding the last parameter. It takes an optional step parameter also where you can specify the difference between adjacent numbers in resulting output. If empty means the step is 1.