Python, list condition in range - python

I need help to search a value in a range inside a list
list.append((5,range(10,15)))
if (5,12) in list :
Print("yes")

Use all
Ex:
l = (5,range(10,15))
check = (5,12)
if all([check[0] == l[0] and check[1] in l[1]]):
print("Ok")
Output:
Ok

Make the second range as a list and you can do it this way-
result = any(elem in list1 for elem in list2)
where result is True or False

Perhaps you're looking for something like this?
mylist = []
mylist.extend(list(range(10, 15)) + [5])
check_list = [5, 12]
if all([z in mylist for z in check_list]):
print('yes')
Output:
yes

Try this :
list_1 = []
for i in range(10,15):
list_1.append((5,i))
if (5,12) in list_1:
print("yes")
If list_1 not an existing list you can do like this:
list_1 = [(5,i) for i in range(10,15)]

Related

Comparing lists with lists of lists

How can I check if a string of list2 is insinde a string of a list of list1?
For example:
list1 = [["CATTAC"], ["AGGA"]]
list2 = ["AT", "GG"]
A simple solution using loops
list1 = [["CATTAC"], ["AGGA"]]
list2 = ["AT", "GG"]
for x in range(len(list1)):
for y in range(len(list2)):
if str(list1[x]).find(str(list2[y])) == -1 :
print("NO")
else :
print("YES")
Function returns true if element of list2 exists in list1
def my_find(list1, list2):
for cur in list2:
for cur_list in list1:
if cur in cur_list:
return True
return False
here you go:
list1 = [["CATTAC"], ["AGGA"]]
list2 = ["AT", "GG"]
res = [[l in e[0] for l in list2] for e in list1]

How do i find one list in another list with python?

I have two lists:
lista=[1,2,3,4,5,6,1,3,2,5,6]
listb=[3,4,5]
I want to find the first occurrence of the elements of listb in the order of listb in lista.
I have tried
print(lista.index(listb))
but it gives the error
ValueError: [3, 4, 5] is not in list
I have also tried
np.where(np.array(lista)==np.array(listb))
but it returns
(array([], dtype=int64),)
What am I doing wrong?
The intended output with lista and listb should be 2.
You can use a simple list comprehension:
lista=[1,2,3,4,5,6,1,3,2,5,6]
listb=[3,4,5]
[print(f"Index = {x}") for x in range(len(lista)) if lista[x:x+3] == listb]
Output:
Index = 2
If you need index position of your listb in lista.
Code
lista=[1,2,3,4,5,6,1,3,2,5,6]
listb=[3,4,5]
for i in listb:
if i in lista:
print (lista.index(i))
Output:
2
3
4
print([lista.index(n) for n in listb])
flag2 = False
for i in lista:
if listb[0] == i:
c = lista.index(i)
k = c
flag = True
for j in range(len(listb)):
if listb[j] != lista[c]:
flag = False
break
c = c+1
if flag:
flag2 = True
print(k)
break
if not flag2:
print('Does not exist')

Pop a largest number in a list to another list, python

I want to get the max() nubmer in a list and then pop it to another list, (list1).
x = [66,1,4,3,6,55]
list1 = []
for i in x:
x.pop(max(x))
#poped item saved to list1
print(list1)
This is my approach but i get the error " pop index out of range". What am i doing wrong ? And i really dont know how to further pop() an item and return it to an empty list.The result should be a list1 with numbers from highest to lowest. Please, dont post any other algorithm with built in functions like sort(). Thanks.
You need to provide the index of the max element in a list to pop
x = [66,1,4,3,6,55]
list1 = [x.pop(x.index(max(x)))]
print(list1)
Output
[66]
Request from Comments:
x = [66,1,4,3,6,55]
list1 = []
while x:
list1.append(x.pop(x.index(max(x))))
print(list1)
In python pop method's argument is index, But you are passing values.
x = [66,1,4,3,6,55]
list1 = []
for i in range(len(x)):
list1.append(x.pop(x.index(max(x))))
print(list1)
Try this.
You can try:
>>> x = [66,1,4,3,6,55]
>>> list_popped = []
>>> list_popped.append(x.pop(x.index(max(x))))
>>> print list_popped
[66]
>>> print x
[1, 4, 3, 6, 55]
List pop method takes index of the element as argument. you are providing the item itself. In your example the first value will be 66 and you are trying pop(66), there is no item at 66th index(the length of the list is less than 66).
try the following code
x = [66,1,4,3,6,55]
list1 = []
for i in range(len(x)):
max_val = max(x)
max_val_index = x.index(max_val)
list1.append(max_val)
x.pop(max_val_index)
print(list1)
Output: [66, 55, 6, 4, 3, 1]

Compare two python lists and expand the shorter list to the length of the longer list

The question header I have is a little confusing and I just wasn't sure how too explain it well with just the header.
I have two lists.
list_1 = [10,20,30,40,50,60,70,80,90]
list_2 = [10,40,70]
Expected output:
new_list = [10,0,0,40,0,0,70,0,0]
How should I do this? The following is what I have and I wasn't sure what was wrong:
def expand_list(complete_list, to_be_expand_list):
expanded_list = []
for i in complete_list:
for j in to_be_expand_list:
if i == j:
expanded_list.append(j)
else:
if expanded_list[-1] != 0:
expanded_list.append(0)
return expanded_list
Try something like this:
def expand_list(full_list, short_list):
return [x if x in short_list else 0 for x in full_list]
This uses a list comprehension to generate a list which is the length of the complete list, but contains only those elements which were in the short list, replacing all the rest with zeroes.
list_1 = [10,20,30,40,50,60,70,80,90]
list_2 = [10,40,70]
new_list = list_1[:]
for i, v in enumerate(list_1):
if v not in list_2:
new_list[i] = 0
print new_list
result:
[10, 0, 0, 40, 0, 0, 70, 0, 0]
This checks the positions in list_1 which aren't in list_2, and sets them to 0
You are going over all the to_be_expand_list for each item on the complete_list and in (almost) each iteration you append an item, so at the end you will have len(list1)*len(list2) items.
You should change it to:
def expand_list(complete_list, to_be_expand_list):
expanded_list = []
for i in complete_list:
if i in be_expand_list:
expanded_list.append(i)
else:
expanded_list.append(0)
return expanded_list
If you look for simpler approach you can use list comprehension:
[x if x in list2 else 0 for x in list1]

How to get item's position in a list?

I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?
Example:
testlist = [1,2,3,5,3,1,2,1,6]
for item in testlist:
if item == 1:
print position
Hmmm. There was an answer with a list comprehension here, but it's disappeared.
Here:
[i for i,x in enumerate(testlist) if x == 1]
Example:
>>> testlist
[1, 2, 3, 5, 3, 1, 2, 1, 6]
>>> [i for i,x in enumerate(testlist) if x == 1]
[0, 5, 7]
Update:
Okay, you want a generator expression, we'll have a generator expression. Here's the list comprehension again, in a for loop:
>>> for i in [i for i,x in enumerate(testlist) if x == 1]:
... print i
...
0
5
7
Now we'll construct a generator...
>>> (i for i,x in enumerate(testlist) if x == 1)
<generator object at 0x6b508>
>>> for i in (i for i,x in enumerate(testlist) if x == 1):
... print i
...
0
5
7
and niftily enough, we can assign that to a variable, and use it from there...
>>> gen = (i for i,x in enumerate(testlist) if x == 1)
>>> for i in gen: print i
...
0
5
7
And to think I used to write FORTRAN.
What about the following?
print testlist.index(element)
If you are not sure whether the element to look for is actually in the list, you can add a preliminary check, like
if element in testlist:
print testlist.index(element)
or
print(testlist.index(element) if element in testlist else None)
or the "pythonic way", which I don't like so much because code is less clear, but sometimes is more efficient,
try:
print testlist.index(element)
except ValueError:
pass
Use enumerate:
testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
if item == 1:
print position
for i in xrange(len(testlist)):
if testlist[i] == 1:
print i
xrange instead of range as requested (see comments).
Here is another way to do this:
try:
id = testlist.index('1')
print testlist[id]
except ValueError:
print "Not Found"
Try the below:
testlist = [1,2,3,5,3,1,2,1,6]
position=0
for i in testlist:
if i == 1:
print(position)
position=position+1
[x for x in range(len(testlist)) if testlist[x]==1]
If your list got large enough and you only expected to find the value in a sparse number of indices, consider that this code could execute much faster because you don't have to iterate every value in the list.
lookingFor = 1
i = 0
index = 0
try:
while i < len(testlist):
index = testlist.index(lookingFor,i)
i = index + 1
print index
except ValueError: #testlist.index() cannot find lookingFor
pass
If you expect to find the value a lot you should probably just append "index" to a list and print the list at the end to save time per iteration.
I think that it might be useful to use the curselection() method from thte Tkinter library:
from Tkinter import *
listbox.curselection()
This method works on Tkinter listbox widgets, so you'll need to construct one of them instead of a list.
This will return a position like this:
('0',) (although later versions of Tkinter may return a list of ints instead)
Which is for the first position and the number will change according to the item position.
For more information, see this page:
http://effbot.org/tkinterbook/listbox.htm
Greetings.
Why complicate things?
testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
if item == 1:
print position
Just to illustrate complete example along with the input_list which has searies1 (example: input_list[0]) in which you want to do a lookup of series2 (example: input_list[1]) and get indexes of series2 if it exists in series1.
Note: Your certain condition will go in lambda expression if conditions are simple
input_list = [[1,2,3,4,5,6,7],[1,3,7]]
series1 = input_list[0]
series2 = input_list[1]
idx_list = list(map(lambda item: series1.index(item) if item in series1 else None, series2))
print(idx_list)
output:
[0, 2, 6]
l = list(map(int,input().split(",")))
num = int(input())
for i in range(len(l)):
if l[i] == num:
print(i)
Explanation:
Taken a list of integer "l" (separated by commas) in line 1.
Taken a integer "num" in line 2.
Used for loop in line 3 to traverse inside the list and checking if numbers(of the list) meets the given number(num) then it will print the index of the number inside the list.
testlist = [1,2,3,5,3,1,2,1,6]
num = 1
for item in range(len(testlist)):
if testlist[item] == num:
print(item)
testlist = [1,2,3,5,3,1,2,1,6]
for id, value in enumerate(testlist):
if id == 1:
print testlist[id]
I guess that it's exacly what you want. ;-)
'id' will be always the index of the values on the list.

Categories