How To Filter Lists By Index In Python

While doing the CodingBat challenges this morning, I challenged myself to refactor each of the solutions into one line of code (if possible). I was doing great, until I ran into this problem:

Given a string, return a new string made of every other char starting with the first, so “Hello” yields “Hlo”.

string_bits(‘Hello’) → ‘Hlo’
string_bits(‘Hi’) → ‘H’
string_bits(‘Heeololeo’) → ‘Hello’

Here is my first attempt:

The first priority is getting the code to work, so I came up with the following long solution, which also happened to be the solution provided by CodingBat (I’m glad I’m on the right track!):

def string_bits(str):
  new_str = ""
  for i in range(len(str)):
    if i % 2 == 0:
      new_str += str[i]
  return new_str

Obviously, I was not very happy with this solution. It is 5 lines of code within the method and just doesn’t look or feel that great to be honest. In Ruby, I can easily make this into one line of code with the collect or map method! There’s got to be a better Python solution!

Luckily, there is! Here is how I refactored this into one line of code:

def string_bits(str):
  return ''.join([str[i] for i in range(len(str)) if i % 2 == 0])

Can you think of an alternative one-line solution to this problem? I’d love to see it!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.