I am beginner in Python.
I wrote the code because I wanted to try sorting using the lambda function without a function.
I tried to sort the list by receiving the length of a, but this error occurred.
I interpreted the words of the error below to mean that it must be in the form of a list.
Is that correct?
strings = ['bob', 'charles', 'alexander3', 'teddy']
for i in strings:
a = len(i) # 3 7 10 5
a.sort()
print(a)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [53], in <cell line: 3>()
3 for i in strings:
4 a = len(i)
----> 5 a.sort()
6 print(a)
AttributeError: 'int' object has no attribute 'sort'
And this is the code I modified accordingly. Is this way right?
strings = ['bob', 'charles', 'alexander3', 'teddy']
b = []
for i in strings:
a = len(i)
b.append(a)
print(b)
However, I need to make a code that outputs the corresponding letter to see if I took the wrong direction, but I'm not doing it well.
strings = ['bob', 'charles', 'alexander3', 'teddy']
strings.sort(key=lambda x:len(x))
print(strings)
---------------------------------------------------------------------------
['bob', 'teddy', 'charles', 'alexander3']
I would like to reproduce this code without a lambda function. How can I do this? I would appreciate it if you could let me know.
.sort()'skey=parameter, which has to be a callable object of some sort. It could be a normaldeffunction, or an instance of a class with a__call__()method, butlambdais perfect for a tiny function like this, used at a single point in your program. Why do you feel the need to avoid its use?strings.sort(key=len). Wrappinglenin a lambda expression that just callslenwith the exact same arguments is unnecessary; you use a lambda to define a new function, andlenis already a function that does exactly what you want.