Home > Mobile >  Checking the last element of multiple lists
Checking the last element of multiple lists

Time:11-30

How can i check the last letter in a string that is the last element of multiple lists? I want to see if the last element of eight different lists are the same, if they are not i want to throw out an error and let the user try again. The point of the function i want to make is that if there are no lists with this last element the function should print something like ("Does not") As you can see in the example this should work because e is present as the last element in "Tie" and "he".

pile1=["vapor","Tie"]
pile2=["stone","he"]
pile3=["glass","sto"]

piles=pile1,pile2,pile3
def lose():
    for pile in piles:
        #here it should go through the last element and last letter in the string of everything in bunke
            print("Does not work")
lose()


  

CodePudding user response:

Slicing! This refers to the indexing of characters

String, technically, is a list of characters. So this works not only for accessing whole elements of lists, but characters of String.

Try out this code and see what it gives you. You may need to alter it, if I have misunderstood the specifics.

for pile in piles:
    print(pile[-1][-1])

CodePudding user response:

Build a list of all last letter of all last word of each pile then create a set with this list. Now, if the length of this set is not 1 there are, at least, two different letters:

if len(set([pile[-1][-1] for pile in piles])) > 1:
    print('Does not')

# Output:
Does not

In your example:

>>> [pile[-1][-1] for pile in piles]
['e', 'e', 'o']

>>> set([pile[-1][-1] for pile in piles])
{'e', 'o'}
  • Related