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
It is because when you are using for loops like you did,
elewill contain the string itself. You can't use it to access the elements of the list. You can use it directly as an string.If you want to have access using indices, you can use
rangeinside for loop :Altough there is no need to convert your int array to str array. You can find these numbers by dividing them by
10.If you don't want to use for-loops you can find these numbers using
lambdaandfilter:resultwill be a list that contains[44, 4, 34, 94].