datguywelbs123
datguywelbs123

Reputation: 33

Check if each element in the last few positions of a list are in another list

I have looked around and not found a question asking about the last items in a list rather than the whole list. I am trying to do something if one of the last items in a list are in another list.

pile = [2,6,9]

another = [1,5,6,5,4,1,6,7]

if another[-1:-4:-1] in pile:  #if one of the last 3 items in 'another' are in the list 'pile' then print yes

    print("yes")
else:

    print("no")

I tried to use slicing but I don't think its the right way to do it, I'm new to this btw. I'm trying to make the program get the last 3 items in the list 'another', and if one of the last 3 elements is in the other list 'pile' print yes. In this case, 6 is within 'another[-1:-4:-1]' and in 'pile', but I don't know how to write it in code so that it works

I used this basic example to try and explain it, but in the program that I am writing, new items are appended onto the list 'another' so the indexes of the last items will change. I only need to check the last items and not the rest of the items.

Upvotes: 2

Views: 39

Answers (2)

SpghttCd
SpghttCd

Reputation: 10850

You can use sets, which allow testing for intersection:

if set(pile).intersection(set(another[-3:])):
    print("yes")
else:
    print("no")

Upvotes: 1

Rachit Bhargava
Rachit Bhargava

Reputation: 168

Well, I would recommend going ahead with slicing off the last three elements of the list and checking them in pile. That's one of the simplest ways to solve this problem and a good approach to go ahead with (while you are still learning how to play with Python).

Here's what I might do.

checker = True  ## variable to keep track of whether or not was 'yes' printed and prevent re-printing of 'yes' in cases when multiple elements satisfy the condition

for num in another[-4:]:
    if num in pile and checker:
        print ('yes')
        checker = False

if checker:
    print ('no')

Upvotes: 0

Related Questions