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


Groups > comp.lang.python > #36743

Re: For Loop in List

Date 2013-01-13 12:41 -0500
From Mitya Sirenef <msirenef@lightbird.net>
Subject Re: For Loop in List
References <f14eb990-b951-4e57-bc70-4a85f837aa51@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.474.1358098902.2939.python-list@python.org> (permalink)

Show all headers | View raw


On 01/13/2013 07:45 AM, 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
> [1, 2, 3]
>
> If I want to iterate the list, I may do as,
>
>>>> for i in list1:
> 	print "Iterated Value Is:",i
>
> 	
> Iterated Value Is: 1
> Iterated Value Is: 2
> Iterated Value Is: 3
> Iterated Value Is: 4
> Iterated Value Is: 5
> Iterated Value Is: 6
> Iterated Value Is: 7
> Iterated Value Is: 8
> Iterated Value Is: 9
> Iterated Value Is: 10
> Iterated Value Is: 11
> Iterated Value Is: 12
>
> 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]
>
> But if I do this I get a Syntax Error, is there a solution?
>
> If anyone of the learned members may kindly let me know?
>
> Apology for any indentation error,etc.
>
> Thanking You in Advance,
>
> Regards,
> Subhabrata
>
> 	
>
>


Another good answer is to use a recipe from itertools docs page.
There are a lot of good recipes there and you may want to keep
them all in a module you can import from when needed. Here
is the recipe:

def grouper(n, iterable, fillvalue=None):
     """From itertools recipes: collect data into fixed-length chunks or 
blocks."""
     # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
     args = [iter(iterable)] * n
     return zip_longest(fillvalue=fillvalue, *args)

 >>> list(grouper(3, range(12))
...
...
...
... )
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]


HTH, - mitya


-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Back to comp.lang.python | Previous | NextPrevious 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