title: Efficient way to swap bytes in python
body: <p>I have some <code>bytearray</code> with length of <code>2*n</code>:</p>
  
  <pre><code>a1 a2 b1 b2 c1 c2
  </code></pre>
  
  <p>I need to switch bytes endian in each 2-byte word, and make:</p>
  
  <pre><code>a2 a1 b2 b1 c2 c1
  </code></pre>
  
  <p>Now I use next approach but it is very slow for my task:</p>
  
  <pre><code>converted = bytearray([])
  for i in range(int(len(chunk)/2)):
     converted += bytearray([ chunk[i*2+1], chunk[i*2] ])
  </code></pre>
  
  <p>Is it possible to switch endian of <code>bytearray</code> by calling some system/libc function?</p>
  
  <hr>
  
  <p>Ok, thanks to all, I timed some suggestions:</p>
  
  <pre><code>import timeit
  
  test = [
  """
  converted = bytearray([])
  for i in range(int(len(chunk)/2)):
     converted += bytearray([ chunk[i*2+1], chunk[i*2] ])
  """,
  """
  for i in range(0, len(chunk), 2):
      chunk[i], chunk[i+1] = chunk[i+1], chunk[i]
  """,
  """
  byteswapped = bytearray([0]) * len(chunk)
  byteswapped[0::2] = chunk[1::2]
  byteswapped[1::2] = chunk[0::2]
  """,
  """
  chunk[0::2], chunk[1::2] = chunk[1::2], chunk[0::2]
  """
  ]
  
  for t in test:
      print(timeit.timeit(t, setup='chunk = bytearray([1]*10)'))
  </code></pre>
  
  <p>and result is:</p>
  
  <pre><code>$ python ti.py
  11.6219761372
  2.61883187294
  3.47194099426
  1.66421198845
  </code></pre>
  
  <p>So in-pace slice assignment with a step of 2 now is fastest. Also thanks to Mr. F for detailed explaining but I not yet tried it because of <code>numpy</code></p>