# [Tutor] counting elements in list

Steven D'Aprano steve at pearwood.info
Wed Sep 15 22:36:51 CEST 2010

```On Thu, 16 Sep 2010 03:23:01 am Shashwat Anand wrote:
> On Wed, Sep 15, 2010 at 1:14 PM, kumar s <ps_python at yahoo.com> wrote:
> > Hi group:
> >
> > I have a list:
> >
> >  k = ['T', 'C', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'C', 'T', 'T',
> > 'T', 'C', 'T',
> > 'T', 'T', 'C', 'C', 'T', 'T', 'T', 'C', 'T', 'T', 'T', 'T', 'T',
> > 'T']
> >
> > the allowed elements are A or T or G or C. List can have any number
> > of A or T or
> > G or C
> >
> > My aim is to get a string ouput with counts of each type A or T or
> > G or C.
> >
> > A:0\tT:23\tG:0\tC:6
> >
> > from the above example, I could count T and C and since there are
> > no A and G, I
> > want to print 0 for them. I just dont know how this can be done.
> >
> >>> k = ['T', 'C', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'C', 'T', 'T',
> >>> 'T',
>
> 'C', 'T', 'T', 'T', 'C', 'C', 'T', 'T','T', 'C', 'T', 'T', 'T', 'T',
> 'T', 'T']
>
> >>> "\t".join(x+":"+str(k.count(x)) for x in 'ATGC')
> 'A:0\tT:23\tG:0\tC:6'

Given the extremely low-level of knowledge which the Original Poster's
question reveals, I think a one-liner like that will probably look
completely cryptic and mysterious.

I suggest a simple modification of the OP's code:

d = {}
for i in set(k):
d[i] = k.count(i)

for key in 'ATGC':
print key + '\t' + str(d.get(key, 0))

--
Steven D'Aprano
```