Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Derek Derek
8,744 PointsPython list - separate elements by odd/even index
Hello,
I am trying to solve a question in python that goes like this:
You are given a string, for example, "abcdefg"
and you want to output
a c e g
bdf
Note that there is a space in between each letters in the first output.
How would you write it in python?
My attempt was to create two lists and add to them depending on each letter's index using modulo 2. But I am getting errors..
def separate_string(sentence):
l = list(sentence)
l2 = list()
for letter in range(l):
index = l.index(letter)
if index % 2 != 0:
l2.append(l[letter])
l.remove(letter)
separate_string('abcedfg')
Thank you for your help!
1 Answer

Quentin Durantay
17,880 PointsHi,
I think your code would be clearer if you use different lists and strings for all your needs. Also, I would prefer to use a count variable here for index and not use range, as it's easier to loop through the initial list, and not its range. Also, don't use index as it will break if you have repetition of letters in your sentence, as index returns the first occurence of the letter only.
Try this instead for example:
def separate_string(sentence):
l = list(sentence)
list_even = list()
list_odd = list()
index = 0
for letter in l:
if index % 2 != 0:
list_even.append(letter)
else:
list_odd.append(letter)
index += 1
string_even = "".join(list_even)
string_odd = " ".join(list_odd)
print(string_odd)
print(string_even)
separate_string('abcdefg')