Reputation: 89
I have a list with different combinations, i.e:
list1 = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
I also have another list, in my case one looking like:
list2 = [1,1]
What I would like to do is to take the two values of list2
, put them together as (1,1)
, and compare them with the elements in list1
, then returning the index. My current attempt is looking like this:
def return_index(comb):
try:
return comb_leaves.index(comb)
except ValueError:
print("no such value")
Unfortunately, it cant find it, because it's not a sequence. Anyone with any good idea of how to fix this?
Upvotes: 0
Views: 194
Reputation: 114320
You are confusing "sequence" with "tuple". Lists and tuples are both sequences. Informally, a sequence is anything that has a length and supports direct indexing in addition to being iterable. A range
object is considered to be a sequence too for example.
To create a two element tuple from any other sequence, use the constructor:
test_element = tuple(list_2)
Upvotes: 4
Reputation: 3671
list1 = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
list2 = [1,1]
tup2 = tuple(list2)
list1.append(tup2)
print('list1:',list1)
print('index:', list1.index(tup2))
will give this:
list1: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (1, 1)]
index: 4
Not sure if unconditionally adding tup2
is what you want.
Maybe you ask for the index, if the 2nd list is in list1:
list1 = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]list2 = [1,1]
tup2 = tuple(list2)
if tup2 in list1:
print('index:', list1.index(tup2))
else:
print('not found')
That gives:
index: 4
the index
function returns the first element that matches.
Upvotes: 1
Reputation: 16593
Try this:
list1 = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
list2 = [1, 1]
def return_index(comb):
try:
return list1.index(tuple(comb))
except ValueError:
print("Item not found")
print(return_index(list2)) # 4
With this line:
list1.index(tuple(list2))
Convert list2
into a tuple
from a list
. list1
's elements are tuples, so to make the comparison, list2
needs to be a tuple
. tuple(list2)
turns [1, 1]
into (1, 1)
(the same type as the elements of list1
).
Upvotes: 1