Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #36733

Re: For Loop in List

Date 2013-01-13 07:29 -0600
From Tim Chase <python.list@tim.thechases.com>
Subject Re: For Loop in List
References <f14eb990-b951-4e57-bc70-4a85f837aa51@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.466.1358083679.2939.python-list@python.org> (permalink)

Show all headers | View raw


On 01/13/13 06:45, subhabangalore@gmail.com wrote:
> Dear Group,
>
> I have a list like,
>
>>>> list1=[1,2,3,4,5,6,7,8,9,10,11,12]
>
> Now, if I want to take a slice of it, I can.
> It may be done in,
>>>> list2=list1[:3]
>>>> print list2
[snip]
> Now, I want to combine iterator with a slicing condition like
>
>>>> for i=list2 in list1:
> 	print "Iterated Value Is:",i
>
> So, that I get the list in the slices like,
> [1,2,3]
> [4,5,6]
> [7,8,9]
> [10,11,12]

Well, you get a SyntaxError because, well, it's a syntax error.  It 
may take a little math to do this:

 >>> SIZE = 3
 >>> for i in range(len(list1)//SICE):
...     print list1[i*SIZE:i*SIZE+SIZE]
...
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10, 11, 12]

Or, you can exploit the fact that iterators exhaust inside a for-loop:

 >>> i = iter(list1)
 >>> for item in i:
...     print [item, i.next(), i.next()]
...
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10, 11, 12]



Hope this helps,

-tkc


Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

For Loop in List subhabangalore@gmail.com - 2013-01-13 04:45 -0800
  Re: For Loop in List Dave Angel <d@davea.name> - 2013-01-13 08:20 -0500
  Re: For Loop in List Tim Chase <python.list@tim.thechases.com> - 2013-01-13 07:29 -0600
  Re: For Loop in List Boris FELD <lothiraldan@gmail.com> - 2013-01-13 14:48 +0100
  Re: For Loop in List Tim Chase <python.list@tim.thechases.com> - 2013-01-13 08:07 -0600
  Re: For Loop in List Mitya Sirenef <msirenef@lightbird.net> - 2013-01-13 12:41 -0500

csiph-web