2

Below I have created a function which iterates through a list of numbers and selects the last 3 digits from each numbers and puts them as new numbers in another list.I also sort them from smallest to largest.However, I see a "TypeError: 'int' object is not iterable" message. What is wrong with my code? Also how could. we do the same thing with a lambda function?

ids = [1600,1500,1800,1900,1700]
alist=ids
sorted_ids=[]
def last_four(alist):
    for element in alist: 
        values=str(element)
        sorted_ids.append(values[1:4])
    return sorted(sorted_ids)

print(last_four(alist))

Code above

Thank you very much!

DMach
  • 71
  • 1
  • 6
  • To select the last 3 digits you can use `str(value)[:-3]` instead of `str(value)[1:4]`. This way no matter the length of the number it always take the last 3 digits – Lwi Jun 11 '20 at 10:09

2 Answers2

1
ids = [1600,1500,1800,1900,1700]
alist=ids
sorted_ids=[]
def last_four(alist):
    for element in alist: 
        values=str(element)
        sorted_ids.append(values[1:4])
    return sorted(sorted_ids)

print(last_four(alist))

results in : enter image description here

for your second question here is the code

last_four = list(map(lambda element: str(element)[1:4], alist))
print(sorted(last_four))
developer101
  • 118
  • 7
1

Your code seems to works well already.

If you want to use lambda, you can write your code something like this. (Which is same with the answer posted, only the difference is that you can immediately use sorted function without deliberately converting a map object into a list object.)

def main():
    ids = [1600, 1500, 1800, 1900, 1700]
    alist = ids
    sorted_last_four = sorted(map(lambda element: str(element)[1:4], alist))
    print(sorted_last_four)


if __name__ == '__main__':
    main()

If you are not familiar with using lambda, or you want to get some intuition of how to use lambda and sorted functions together, you can read this answer posted.

Good luck.

kimDragonHyeon
  • 414
  • 5
  • 9