Path: csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Paul Rubin Newsgroups: comp.lang.python Subject: Re: Convert list to another form but providing same information Date: Mon, 21 Mar 2016 18:35:12 -0700 Organization: A noiseless patient Spider Lines: 21 Message-ID: <87twjzz44v.fsf@jester.gateway.pace.com> References: <1010f2cb-21f9-495b-8af4-03ad209b4c1e@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="3c7a0b0f75f6c95b248ff930d17c36e7"; logging-data="12413"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+1L9WSbLUkds9YJmZTrjaE" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux) Cancel-Lock: sha1:xRh//jt4lNvy8YDS8Zflp/hwazE= sha1:6jBGJlFpTMh5wTOWEoXrqUr0li4= Xref: csiph.com comp.lang.python:105432 Maurice writes: > I have a list such [6,19,19,21,21,21] > Therefore the resulting list should be: > [0,0,0,0,0,0,1,0,0,0...,2,0,3,0...0] Rather than a sparse list you'd typically want a dictionary (untested): from collections import defaultdict the_list = [0,0,0,0,0,0,1,0,0,0...,2,0,3,0...0] ... days = defaultdict(int) for t in the_list: days[t] += 1 this results in days being the defaultdict { 6:1, 19:2, 21:3 }. defaultdict is a special type of dictionary where if you try to access a non-existent element, it gets created and initialized with the data constructor you made it with. In this case the data constructor is int, and int() makes the number 0, so the defaultdict elements are initialized to 0.