By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,267 Members | 1,800 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,267 IT Pros & Developers. It's quick & easy.

how do I sort a list of names?

P: 23
I need to sort a list of first and last names from shortest to longest.
for example:
[John Doe, Jane Smith, Jane Doe]

I have to write a function to find the longest name but noe sure how to do it!
Nov 30 '10 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 2.5K+
P: 2,851
In Python 2.3:
Expand|Select|Wrap|Line Numbers
  1. >>> names = ["John Doe", "Jane Smith", "Jane Doe", "Jo Nu"]
  2. >>> names.sort(lambda x, y: cmp(len(x), len(y)))
  3. >>> names
  4. ['Jo Nu', 'John Doe', 'Jane Doe', 'Jane Smith']
  5. >>> 
Dec 1 '10 #2

Expert 100+
P: 622
I have to write a function to find the longest name but no(t) sure how to do it!
Do you want to sort or to find the longest name. Sorting the entire list just to find one item is very inefficient and if I was your instructor, would be rejected as too inefficient to be a viable solution.
Expand|Select|Wrap|Line Numbers
  1. ##   does not allow for multiple names that are longest
  2. names = ['Jon Doe', 'Jane Smith', 'Jane Doe']
  3. longest_name = names[0]
  4. longest = len(names[0])
  6. for name in names:
  7.     if len(name) > longest:
  8.         longest = len(name)
  9.         longest_name = name
  10. print longest_name, longest 
Dec 1 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.