Jay Cutler
Jay Cutler

Reputation: 7

How to add repeats of the same element to list by comparing index in Python?

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!

Upvotes: 0

Views: 48

Answers (4)

Hackaholic
Hackaholic

Reputation: 19743

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']

Upvotes: 0

Michael Lorton
Michael Lorton

Reputation: 44386

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

Upvotes: 0

heemayl
heemayl

Reputation: 42017

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'.

Upvotes: 1

ahendrickson
ahendrickson

Reputation: 74

I think this is what you're after

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

Upvotes: 0

Related Questions