Python Forum
Sort() Question / Getting Error
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sort() Question / Getting Error
#1
Hi... I am relatively new to Python... I find it very interesting coming originally from a mainframe background. 
I have a question.  I'm trying to do a special sort on a list of tuples... Do I need to import anything 
in order to use a lamda?  I'm getting the following error message - any ideas why?

File "tuples.py", line 4 
  copied_list.sort(key=lamda x: (not x[0], x[1]))
                                            ^

Here is the code I have so far: 

my_list = [(False, 'a'),(False, 'd'),(True, ''),(False,'h'),(True,'g')]

copied_list = my_list.copy()
copied_list.sort(key=lamda x: (not x[0], x[1]))

print copied_list
Reply
#2
In [1]: my_list = [(False, 'a'),(False, 'd'),(True, ''),(False,'h'),(True,'g')]

In [2]: my_list.sort(key=lambda l: l[0])

In [3]: my_list
Out[3]: [(False, 'a'), (False, 'd'), (False, 'h'), (True, ''), (True, 'g')]
This will sort the list by the first element of the tuple/list
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
sort() as wavic show dos a in place sort of original list.
sorted() return a new sorted list,with this no need to copy() as you do.
>>> help(list.sort)
Help on method_descriptor:

sort(...)
    L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

>>> help(sorted)
Help on built-in function sorted in module builtins:

sorted(...)
    sorted(iterable, key=None, reverse=False) --> new sorted list

>>> my_list = [(False, 'a'),(False, 'd'),(True, ''),(False,'h'),(True,'g')]
>>> sorted(my_list, key=lambda x:  x[1])
[(True, ''), (False, 'a'), (False, 'd'), (True, 'g'), (False, 'h')]

>>> # my_list is unchanged
>>> my_list
[(False, 'a'), (False, 'd'), (True, ''), (False, 'h'), (True, 'g')]
Reply
#4
I didn't see that he is copping the list  Big Grin

I need a rest
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Photo a.sort() == b.sort() all the time 3lnyn0 1 1,277 Apr-19-2022, 06:50 PM
Last Post: Gribouillis
  syntax error on list.sort() jjordan33 3 3,146 Jul-10-2019, 04:57 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020