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

Python

Gary Gibson
Gary Gibson
5,011 Points

Trying to take out every other item in a list.

I'm stuck writing a simple code that takes every other item out of an iterable and puts it in a new list. For example, in the string "abacadabra", I want to create "aaaar".

Here's what I've tried:

word = 'abacadabra'
result = ''
for i in word:
    if word.index(i) % 2 == 0:
        result += i
print(result)

But instead of getting "aaaar", I get "aaaara".

With other words, I get varying results as far as which letters get left out or repeated depending on whether they appear elsewhere in the word. For example, with "xylophone", I get "xlpe" because the "o" appears in the odds (word.index(i) % 2 == 0 condition is not met and so the "o" gets left out when it is an index that DOES meet that condition.

So what am I missing and how what do I do to fix it?

Would I just have to use a dictionary?

2 Answers

Jacob Bergdahl
Jacob Bergdahl
29,118 Points

It would probably be easier to not use modulo and just do i += 2 instead. This way you don't even need the if statement.

Gary Gibson
Gary Gibson
5,011 Points

Sorry, not sure what that would look like. The i represents the character in the string, right? So it can't be incremented, can it?

And how would that look in the code?

Jacob Bergdahl
Jacob Bergdahl
29,118 Points

Sorry! I just realized I used terminology from different programming languages. There are many ways to solving this problem, but I think the easiest to understand would be this:

word = 'abacadabra'
result = ''
for i in range(0, len(word), 2):
    result += word[i]
print(result)

Here, we turn the for-each loop into a for loop. We start at index 0, end at the length (count) of the string, and the third parameter shows that we increment by two (and thus skip every other) :)

Gary Gibson
Gary Gibson
5,011 Points

Makes sense, Jacob! Thank you.