-3

I have two seperate lists here and don't quite understand the difference between them. Ultimately, I want to sort them, but don't know which data type to use. Both don't work.

mylist = [('Andrew','10')('Jim',"20"),("Sarah","30"),("Jim","23"),("Andrew","54")]
mylist1 = [['Andrew','10']['Jim',"20"],["Sarah","30"],["Jim","23"],["Andrew","54"]]
sorted(mylist)
sorted(mylist1)
print mylist
print mylist1
user2242044
  • 8,803
  • 25
  • 97
  • 164
  • 3
    You're missing a comma in both lines between the 'Andrew' and 'Jim' entries. Also, `sorted` returns a new, sorted copy of the list you pass it; it does not sort in place. It looks like you want `mylist.sort()` and `mylist1.sort()` instead. – jonafato Nov 08 '14 at 00:03
  • `sorted` returns a new sorted copy of your list. Try `print sorted(mylist)`. – khelwood Nov 08 '14 at 00:03
  • You have got a list of tuples and a list of lists - just in addition to @jonafato answer – ha9u63a7 Nov 08 '14 at 00:04
  • What's the actual question here? That code won't even get to the point where you try to sort them. Code that didn't have the same bug would sort just fine. So, if you have a problem with not being able to sort something, give us an [example](http://stackoverflow.com/help/mcve): complete, runnable code that does whatever it is you're asking about, and the output or traceback, and what you wanted it to do instead. – abarnert Nov 08 '14 at 00:25

2 Answers2

1

You have made a typo, omitting a coma between the first and second element:

mylist = [('Andrew','10')('Jim',"20")

Python interpretes this as a call to ('Andrew','10'), but of course tuple is not callable, hence the error.

Moreover, you want rather use mylist.sort() if you want to sort list in place. The sorted() builtin returns a copy, so if you want to use it, you should rather use:

sortedList = sorted(myList)
m.wasowski
  • 6,329
  • 1
  • 23
  • 30
0

The difference between the lists is that one is a list of lists, while the other is a list of tuples. See: What's the difference between lists and tuples? for more information. In this situation there isn't much difference between them.

To sort by name and then number you can simply use mylist.sort().

To sort by number only you can use mylist.sort(key = lambda item: item[1])

Community
  • 1
  • 1
Stuart
  • 9,597
  • 1
  • 21
  • 30