221

I am a bit confused regarding data structure in python; (),[], and {}. I am trying to sort a simple list, probably since I cannot identify the type of data I am failing to sort it.

My list is simple: ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']

My question is what type of data this is, and how to sort the words alphabetically?

Daniel Junglas
  • 5,830
  • 1
  • 5
  • 22
icypy
  • 3,062
  • 5
  • 25
  • 27
  • If you want to sort your list then you can use "list=['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue'] list.sort() print list" . – kannanrbk Dec 25 '12 at 17:11
  • `[]` encloses the builtin datatype `list`, (see http://www.tutorialspoint.com/python/python_lists.htm). Lists are just groups of values (they can contain other iterable objects- i.e nested lists). `()` encloses the builtin `tuple`. They are immutable (cannot be changed). (see http://www.tutorialspoint.com/python/python_tuples.htm). And `{}` encloses the builtin `dictionary`. Parallels with a dictionary (for words), where a 'key' would be the word and the 'value's is the definition. (see http://www.tutorialspoint.com/python/python_dictionary.htm). – Rushy Panchal Dec 25 '12 at 21:17

6 Answers6

321

[] denotes a list, () denotes a tuple and {} denotes a dictionary. You should take a look at the official Python tutorial as these are the very basics of programming in Python.

What you have is a list of strings. You can sort it like this:

In [1]: lst = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']

In [2]: sorted(lst)
Out[2]: ['Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim', 'constitute']

As you can see, words that start with an uppercase letter get preference over those starting with a lowercase letter. If you want to sort them independently, do this:

In [4]: sorted(lst, key=str.lower)
Out[4]: ['constitute', 'Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim']

You can also sort the list in reverse order by doing this:

In [12]: sorted(lst, reverse=True)
Out[12]: ['constitute', 'Whim', 'Stem', 'Sedge', 'Intrigue', 'Eflux']

In [13]: sorted(lst, key=str.lower, reverse=True)
Out[13]: ['Whim', 'Stem', 'Sedge', 'Intrigue', 'Eflux', 'constitute']

Please note: If you work with Python 3, then str is the correct data type for every string that contains human-readable text. However, if you still need to work with Python 2, then you might deal with unicode strings which have the data type unicode in Python 2, and not str. In such a case, if you have a list of unicode strings, you must write key=unicode.lower instead of key=str.lower.

pemistahl
  • 9,304
  • 8
  • 45
  • 75
  • Using the second example on a pymongo `find_one()` result from a MongoDB database, I get error: `descriptor 'lower' requires a 'str' object but received a 'unicode'`. The result is an array of strings and implemented like this: `results['keywords'] = sorted(keywords['keywords'], key=str.lower)`. Does anybody know how to resolve this? – user1063287 Aug 17 '16 at 10:46
  • @user1063287 Sorry for my late response. In your case, you need to write `key=unicode.lower` instead of `key=str.lower`. This is because you are dealing with unicode strings, not byte strings. Please refer to the official [Unicode HOWTO](https://docs.python.org/3/howto/unicode.html) for further information on this, especially for the respective differences between Python 2 and 3. – pemistahl Jan 17 '17 at 13:24
41

Python has a built-in function called sorted, which will give you a sorted list from any iterable you feed it (such as a list ([1,2,3]); a dict ({1:2,3:4}), although it will just return a sorted list of the keys; a set ({1,2,3,4); or a tuple ((1,2,3,4))).

>>> x = [3,2,1]
>>> sorted(x)
[1, 2, 3]
>>> x
[3, 2, 1]

Lists also have a sort method that will perform the sort in-place (x.sort() returns None but changes the x object) .

>>> x = [3,2,1]
>>> x.sort()
>>> x
[1, 2, 3]

Both also take a key argument, which should be a callable (function/lambda) you can use to change what to sort by.
For example, to get a list of (key,value)-pairs from a dict which is sorted by value you can use the following code:

>>> x = {3:2,2:1,1:5}
>>> sorted(x.items(), key=lambda kv: kv[1])  # Items returns a list of `(key,value)`-pairs
[(2, 1), (3, 2), (1, 5)]
InSync
  • 4,851
  • 4
  • 8
  • 30
Teo Klestrup Röijezon
  • 5,097
  • 3
  • 29
  • 37
17

You're dealing with a python list, and sorting it is as easy as doing this.

my_list = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
my_list.sort()
Bryan
  • 6,682
  • 2
  • 17
  • 21
11

You can use built-in sorted function.

print sorted(['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue'])
Fatih Erikli
  • 2,986
  • 2
  • 15
  • 11
5

ListName.sort() will sort it alphabetically. You can add reverse=False/True in the brackets to reverse the order of items: ListName.sort(reverse=False)

Maximilian Kohl
  • 632
  • 1
  • 9
  • 23
Crafter0800
  • 57
  • 1
  • 2
  • 6
3
>>> a = ()
>>> type(a)
<type 'tuple'>
>>> a = []
>>> type(a)
<type 'list'>
>>> a = {}
>>> type(a)
<type 'dict'>
>>> a =  ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue'] 
>>> a.sort()
>>> a
['Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim', 'constitute']
>>> 
shadyabhi
  • 16,675
  • 26
  • 80
  • 131