0

This is regarding a number sorting program. I am not able to understand the syntax with the join line.

#!/usr/bin/env python
import sys
ar=[]
for arg in sys.argv:
    ar.append(arg)  
ar.sort()
print " ".join('%s'%x for x in ar)
pppery
  • 3,731
  • 22
  • 33
  • 46

2 Answers2

1

'%s' % x for x in ar is what is called a generator expression. It generates a bunch of '%s' % x where x is defined as each item in ar." ".join(...) puts a space between each item given to .join(). When the generator is given, it puts a space between each item the generator generates. If ar is not a list of strings, the generator converts each item to a string. Then, we use " ".join(...) to put a space between each of those strings. sys.argv is always a list of strings, so you don't need that generator expression. You could instead use " ".join(sys.argv). According to this answer, it would be more efficient to use a list comprehension anyway. You would also use str(x) instead of "%s"%x just because it's easier to read.

Community
  • 1
  • 1
zondo
  • 19,901
  • 8
  • 44
  • 83
0

I agree that the join line looks super funky.

" ".join(...) will take a list (or any iterable) of arguments and create for you one string where all the arguments arguments are separated by one space.

In this case I would just pass in your sorted list ar.

#!/usr/bin/env python

import sys
ar=[]
for arg in sys.argv:
    ar.append(arg)

ar.sort()
print " ".join(ar)

Now we have two more problems:

  • The first argument on the command line will be the name of your script. I'd use sys.argv[1:] instead of just sys.argv.
  • You're sorting the strings that are passed in, and not the numbers. this will lead to a sort like [1, 11, 13, 2, 3, 4, 5, 56, 9]. To remedy this, I'd use ar.append(int(arg)).
turbulencetoo
  • 3,447
  • 1
  • 27
  • 50
  • 2
    Using `ar.append(int(arg))` will mean that `" ".join(ar)` won't work though. You could avoid the permanent conversion by leaving `ar` as `str`, and doing the sort as `ar.sort(key=int)` so it sorts on `int` values, while preserving the original `str`. – ShadowRanger Apr 06 '16 at 23:30