0

I'm attempting to do work with lists in Python and there is a certain part I've been stuck on:

Objective: Iterate through a master list (alphabet) of x amount of elements, and compare whether the index of said element is a factor of 7. If so, append this element to a new list (final). It seems very simple, and here is the code I've written so far:

def test():

alphabet = ['a', 'a', 'b' 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'li', 'a'] final = []

for letter in alphabet:
    if (alphabet.index(letter) % 7 == 0):
        final.append(letter)

print final

The output I am getting: ['a', 'a', 'g', 'n', 'u', 'a']

The output I am expecting should return a list of every element in the original list that has an index divisible by 7. I cannot figure out how to account for the duplicates.

Any assistance with this would be much appreciated - thank you very much in advance!

4 Answers 4

1

Do:

>>> a = ['a', 'a', 'b' 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'li', 'a']

>>> [j for i,j in enumerate(a) if i%7==0]
['a', 'g', 'n', 'u', 'a']

Note that, on index 2, you have 'b' 'b' which results in 'bb'.

Sign up to request clarification or add additional context in comments.

Comments

0

I think this is what you're after

for index, letter in enumerate(alphabet):
if (index % 7 == 0):
    final.append(letter)
print final

Comments

0

Two things.

First, instead of using a list to accumulate the results, use a set. Duplicates are automatically eliminated.

And, why look at every letter instead of just at every seventh letter?

final = set()
for i in range(len(alphabet)/7):     
   final.add(alphabet[i*7])
print final

Comments

0

try this:

>>> alphabet = ['a', 'a', 'b' 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'li', 'a']
>>> [letter for i,letter in enumerate(alphabet) if i%7==0]
['a', 'g', 'n', 'u', 'a']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.