bnicholl bnicholl -4 years ago 73
Python Question

returning amount of times an element appears in list with for loop. python

DNA = [a,t,g,c]



lis = []

for a in DNA:
for t in DNA:
for g in DNA:
for c in DNA:
lis.append([a,t,g,c])


So I created this for loop with all possible combos of strings 'a','t','g','c' , which returns all 256 combos.

I than created another for loop below, which is supposed to count all of the 'g' strings, which should return a quarter of 256, but it does not do this. It instead returns 256 again, which is the total amount of 'a','t','g','c' strings combined. When I run the below code into a list I
created such as

created_DNA_to_check_code = ['a','g','t','a','g','g']


it returns the proper amount of 'g' strings, which is 3, so I have no idea why it doesn't work right when ran with the above for loop. Any help would be appreciated

def G():
total = 0
for g in lis:
for itr in g:
if itr == 'g':

total += 1
return total
print(G())

Answer Source

You are counting the number of gs, across all the strings so ['g','g','g','g'] would add 4 to your total, which not surprisingly totals 256.

>>> import itertools as it
>>> DNA = ['a','g','t','c']
>>> dna = list(it.product(DNA, repeat=4))
>>> len(dna)
256
>>> sum(len(d) for d in dna)
1024
>>> sum(g.count('g') for g in dna)
256
>>> sum(1 for g in dna if 'g' in g)
175

256 is a quarter of 1024 the total number of strings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download