-2

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.

2
  • 2
    If you want to sort a list by some criteria other than simply comparing the elements, you have to use .sort()'s key= parameter, which has to be a callable object of some sort. It could be a normal def function, or an instance of a class with a __call__() method, but lambda is 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? Commented Dec 30, 2022 at 17:40
  • You could just do strings.sort(key=len). Wrapping len in a lambda expression that just calls len with the exact same arguments is unnecessary; you use a lambda to define a new function, and len is already a function that does exactly what you want. Commented Dec 30, 2022 at 17:45

2 Answers 2

0
strings = ['bob', 'charles', 'alexander3', 'teddy']
sorted(strings,key=len) 

#['bob', 'teddy', 'charles', 'alexander3']

will do without lambda function

Note: It will return a new list

Sign up to request clarification or add additional context in comments.

Comments

0

If for some reason you really don't want to use a sorting function, you can twist things around to use the default sorting:

strings = ['bob', 'charles', 'alexander3', 'teddy']
len_with_strings = [(len(w), w) for w in strings]
sorted_strings = [b for a,b in sorted(len_with_strings)]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.