[Tutor] Sorting a list in ascending order

Martin A. Brown martin at linux-ip.net
Fri Apr 29 17:10:07 EDT 2016


Greetings Ken and welcome to Python,

> Using Linux 2.7.6 in Ubuntu 14.04.4. Thanks.

Thank you for this information.  I have one tip for you:  While 
Python 2.x will still be around for a while, if you are learning 
Python today, I'd suggest Python 3.x. You can read more about the 
differences online (or ask here), if you care.  The only syntax 
difference that usually trips up beginners is the following:

  print line     # Python 2.x
  print(line)    # Python 3.x

Though there are other differences, this is one of the most obvious 
to all Python programmers.  With that said, I'll just answer your 
question using Python 2.x, since everything else in your example 
will work perfectly the same in either version.

I intend to suggest what you should read, and then what you should 
try to run in order to address your question(s).

I will paste my entire interactive Python sessions below.  Did you 
know that you can use the Python interpreter as a shell to test out 
how things behave?  Very handy.  Try typing 'python' at the CLI and 
you should see this:

  $ python
  Python 2.7.8 (default, Sep 30 2014, 15:34:38) [GCC] on linux2
  Type "help", "copyright", "credits" or "license" for more information.
  >>>

So, when you see ">>>" below, that's in the Python shell (2.7.8 in 
my case, 2.7.6 in yours).

> In entering five random number, how can I best sort it into 
> ascending order, such as 0511414453?

OK, so you have five random numbers, but you seem to want to print 
them without any visual space between them.  A bit strange, but OK!

Fragment #1:

> number01 = "41"
> number02 = "11"
> number03 = "05"
> number04 = "53"
> number05 = "44"

Observation:  You define a variable called 'number01', which 
actually contains a string value.  You can call the variable 
anything you want, but that will not change the type of the object 
to which your variable name is bound.  For example:

  >>> number01 = "41"
  >>> type(number01)
  <type 'str'>

Suggestion #1, try this instead:

  >>> number01 = 41
  >>> type(number01)
  <type 'int'>

Ah-ha!  Now, we are dealing with integers (numbers).

Fragment #2:

> line = number01 + number02 + number03 + number04 + number05

Observation:  Since all of the variables (named number01, number02, 
number03, etc....) contain strings, you are using string 
concatenation to create a new string.  After the above command 
executes, you have this:

  >>> line
  '4111055344'
  >>> type(line)
  <type 'str'>

Comment:  You don't really want a string, do you?  Keep reading for 
a moment, and I'll come back to this.

Also, I don't think you really want to add the integers.  That would 
be 41 + 11 + 05 + 53 + 44 = 154.  But, you want to keep the numbers 
and sort them.  We will need to keep them in a list.  And, Python 
has a data structure for you...called, obviously enough list().

Fragment #3:

> print
> print line
> line.sort()
>
> Traceback (most recent call last):
>  File "Mega_Millions_01_Tickets_Entry_TEST_TEST.py", line 11, in <module>
>    print line.sort()
>
> AttributeError: 'str' object has no attribute 'sort'

Observation:  This message is called an Exception, in Python.  
There are many different kinds of exceptions--this one is called 
AttributeError, but the message of the exception is the important 
part for us here.  It doesn't make sense to sort a string.  You can 
sort two strings, of course.  But not a single string.

Anyway, the important thing about the Exception is it tries to give 
you a good deal of information about which line of code did 
something that was problematic, and what code called that code (this 
is why it's called a "Traceback").

Now, I'll rewind to the beginning and try to go through the problem 
again, changing a few pieces of your program to get you closer to 
your solution.

First, let's use the right datatype, an int, for each number. 
Second, let's use a list() to store the numbers (instead of five
  separate named variables; easy to mistype names).
Third, let's sort it.
Then, let's print it.

  >>> nums = [41, 11, 5, 53, 44]  # -- create/populate a list
  >>> nums
  [41, 11, 5, 53, 44]             # -- still looks good
  >>> nums.sort()                 # -- sort, in place!
  >>> nums
  [5, 11, 41, 44, 53]             # -- Ta-da!

I'm going to do the same thing a slightly different way, now, so you 
can see how to add stuff to a list:

  >>> nums = list()
  >>> nums.append(41)
  >>> nums.append(11)
  >>> nums.append(5)
  >>> nums.append(53)
  >>> nums.append(44)
  >>> nums
  [41, 11, 5, 53, 44]

In each case the variable 'nums' still contains the same data.  We 
just got there in a different series of steps.  You may decide which 
makes more sense to you in any given situation.

So, suggestion, play with lists, and see how they work.

Now, we have to figure out how to print the contents of the list.  
Here's one way, but it is not the output you appear to want.

  >>> print nums
  [5, 11, 41, 44, 53]

I'm guessing you want '05 11 41 44 53'.

There are many ways to convert from one data type to another or to 
format the output of something when you want to print it.  So, I 
will show you one or two ways, but there are many ways you could do 
this.  It's good to learn to read them all, but you can always pick 
the one that works best for your situation.

Conversion is one way The 'str' function converts the int (17) into 
a string.  I store that in a variable called string_num.  The 'type' 
function tells us that the contents of the variable string_num are 
of type 'str':

  >>> num = 17
  >>> string_num = str(num)
  >>> string_num
  '17'
  >>> type(string_num)
  <type 'str'>

This is useful, but, we are not going to do that here.

Detour to format strings!  What I'm about to show is how you can  
format a value (usually in preparation for output/printing).

There are many different ways to print numbers, as you may know from 
prior mathematics classes.  (Ignoring some possibly important 
subtleties for a moment,) 1, 1.0, 1e0 are different ways of printing 
the value of 1.

  >>> num = 7
  >>> '%d' % (num,)
  '7'

Let's add a leading zero:

  >>> '%02d' % (num,)
  '07'

I think that's what you want.

Returning to your data, you might be worried about that 5, which was 
missing its leading zero.  Well, as you can see the number is never 
stored with that leading zero.  A number is a number.  However, we 
can produce the leading zero when we print.

  >>> stringified_nums = list()
  >>> for x in nums:
  ...     stringified_nums.append('%02d' % (x,))
  >>> stringified_nums
  ['05', '11', '41', '44', '53']

Lastly, let's print the stringified_nums; do you want to print them 
with colons separating the numbers, semicolons, commas, a hyphen?

  >>> ':'.join(stringified_nums)
  '05:11:41:44:53'
  >>> ','.join(stringified_nums)
  '05,11,41,44,53'

Now, I'm going to put it all together.....

  nums = [41, 11, 5, 53, 44]
  nums.sort()
  outstr = list()
  for x in nums:
      outstr.append('%02d' % (x,))
  print ' '.join(outstr)

Hopefully that made sense to you.  I include a few links to various 
places in the Python project documentation that may help you.  In 
particular, I'd recommend that you read through the Python tutorial 
and keep a Python interactive interpreter open while you do that, so 
you can play with the different datatypes and functions.

If you have more questions, please ask here, there are quite a few 
others who are happy to help.

Best of luck,

-Martin

Tutorial:      https://docs.python.org/2/tutorial/introduction.html
 on numbers:   https://docs.python.org/2/tutorial/introduction.html#numbers
 on strings:   https://docs.python.org/2/tutorial/introduction.html#strings
 on lists:     https://docs.python.org/2/tutorial/introduction.html#lists

Reference:     https://docs.python.org/2/library/index.html
 on datatypes: https://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex
 on sequences: https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange
 on functions: https://docs.python.org/2/library/functions.html

  (A list is a sequence.  There are other types of sequences, but 
  the section on sequences, should give you some idea of how to play 
  with lists.)

-- 
Martin A. Brown
http://linux-ip.net/


More information about the Tutor mailing list