kurdebalans
kurdebalans

Reputation: 27

function to find words that starts and ends with the same letter

i would like to make a function that finds the words that starts - however me code leads to an error: TypeError: 'int' object is not iterable. Any idea why?

list1 = ['ala', 'ma', 'piegi', 'kajak']

def first_last(strings):
    lista = []
    for word in strings:
        if word[0] == word[-1]:
            lista += 1
    return lista

print(first_last(list1))

Upvotes: 1

Views: 454

Answers (2)

distro
distro

Reputation: 712

You can't add one to an empty list. You can add one to another number.

list1 = ['ala', 'ma', 'piegi', 'kajak']

def first_last(strings):
    lista = []
    for word in strings:
        if word[0] == word[-1]:
            lista.append(word)
    return lista

print(first_last(list1))

The code above adds the word itself to your list.

Upvotes: 3

revliscano
revliscano

Reputation: 2272

Returning a list comprehension that includes the items after checking that condition, will be enough:

def first_last(list1):
    return [word for word in list1 if word[0] == word[-1]]

You were getting that error because you were attempting to concatenate the list lista with an integer. You were looking for append() method in your example.

Upvotes: 4

Related Questions