List of numbers converted to list of strings to iterate over it. But receiving TypeError messages

46 views Asked by At

I am trying to find the numbers that ends with 4 in a list of numbers. I tried the following code but getting an error message saying TypeError: list indices must be integers or slices, not str

x = [12, 44, 4, 1, 6, 343, 10, 34, 12, 94, 783, 330, 896, 1, 55]
x_str = list(map(str, x))

for ele in x_str:
    if x_str[ele][-1] == "4":
        print(ele)

I tried to modify the code by making x_str[ele][-1] an integer. But now I am getting another error message saying TypeError: 'int' object is not iterable

x = [12, 44, 4, 1, 6, 343, 10, 34, 12, 94, 783, 330, 896, 1, 55]
x_str = list(map(str, x))

for ele in x_str:
    if int(x_str[ele][-1]) == 4:
        print(ele)

Would be really grateful to receive any help or suggestion

2

There are 2 answers

0
Mohsen_Fatemi On BEST ANSWER

It is because when you are using for loops like you did, ele will contain the string itself. You can't use it to access the elements of the list. You can use it directly as an string.

x = [12, 44, 4, 1, 6, 343, 10, 34, 12, 94, 783, 330, 896, 1, 55]
x_str = list(map(str, x))

for ele in x_str:
    if ele[-1] == "4":
        print(ele)

If you want to have access using indices, you can use range inside for loop :

x = [12, 44, 4, 1, 6, 343, 10, 34, 12, 94, 783, 330, 896, 1, 55]
x_str = list(map(str, x))

for i in range(len(x_str)):
    if x_str[i][-1] == "4":
        print(ele)

Altough there is no need to convert your int array to str array. You can find these numbers by dividing them by 10.

x = [12, 44, 4, 1, 6, 343, 10, 34, 12, 94, 783, 330, 896, 1, 55]

for num in x:
    if num%10 == 4:
        print(num)

If you don't want to use for-loops you can find these numbers using lambda and filter :

x = [12, 44, 4, 1, 6, 343, 10, 34, 12, 94, 783, 330, 896, 1, 55]

result = list(filter(lambda num: num%10==4,x))

result will be a list that contains [44, 4, 34, 94].

0
Meitham On

your loop is the issue, change it to::

for ele in x_str:
    if ele.endswith('4'):
        print(ele)

Because the loop is for each, you don't need the index