[Tutor] for: how to skip items

emile emile at fenx.com
Mon Feb 17 17:49:27 CET 2014


On 02/17/2014 08:05 AM, Gabriele Brambilla wrote:
> Hi,
>
> I'm wondering how I can (if I can) make a for loop in which I don't use all
> the elements.
>
> for example
>
> a100 = list(range(100))
>
> for a in a100:
>               print(a)
>
> it print out to me all the numbers from 0 to 99
> But if I want to display only the numbers 0, 9, 19, 29, 39, ...(one every
> 10 elements) how can I do it WITHOUT defining a new list (my real case is
> not so simple) and WITHOUT building a list of indexes?
>
Look into python's slice notation --

[root at whfw2 root]# python
Python 2.7.1 (r271:86832, Dec  6 2010, 13:47:21)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> a100 = list(range(100))
 >>> a100[::10]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
 >>>


HTH,

Emile






More information about the Tutor mailing list