3

I'm trying to understand what is happening in this piece of code. I can see what it does, but the process for how it gets there eludes me.

from itertools import groupby
lines = '''
This is the
first paragraph.

This is the second.
'''.splitlines()
# Use itertools.groupby and bool to return groups of
# consecutive lines that either have content or don't.
for has_chars, frags in groupby(lines, bool):
    if has_chars:
        print ' '.join(frags)
# PRINTS:
# This is the first paragraph.
# This is the second.

I think my confusion surrounds the multiple variables in the for loop (in this instance has_chars and frags). How are multiple variables possible? What is happening? How is python dealing with multiple variables? What am I saying to python when I put multiple variables in a for loop? Is there a limit to how many variables you can create in a for loop? How can I ask a precise question when I don't understand enough about programming to actually form one?

I've tried running it through the python visualiser to get a better understanding. That thing has never made anything clearer for me. Try as I oft do.

OhNoNotScott
  • 824
  • 2
  • 9
  • 12
  • This post is pretty helpful in understanding how groupby works: http://stackoverflow.com/questions/773/how-do-i-use-pythons-itertools-groupby – frowningpants Jan 08 '14 at 03:54
  • See here: https://github.com/pas-campitiello/python/blob/master/2-NotesSimplePrograms.md#15-lines-itertools – Rawton Evolekam Aug 31 '17 at 23:55

1 Answers1

2

From python-course

As we mentioned earlier, the Python for loop is an iterator based for loop. It steps through the items in any ordered sequence list, i.e. string, lists, tuples, the keys of dictionaries and other iterables. The Python for loop starts with the keyword "for" followed by an arbitrary variable name, which will hold the values of the following sequence object, which is stepped through. The general syntax looks like this:

for <variable> in <sequence>:
    <statements>
else:
    <statements>

Let say you have list of tuples like

In [37]: list1 = [('a', 'b', 123, 'c'), ('d', 'e', 234, 'f'), ('g', 'h', 345, 'i')]

You can iterate over it as,

In [38]: for i in list1:
   ....:     print i
   ....:     
('a', 'b', 123, 'c')
('d', 'e', 234, 'f')
('g', 'h', 345, 'i')

In [39]: for i,j,k,l in list1:
    print i,',', j,',',k,',',l
   ....:     
a , b , 123 , c
d , e , 234 , f
g , h , 345 , i

for k, v in os.environ.items():
... print "%s=%s" % (k, v)

USERPROFILE=C:\Documents and Settings\mpilgrim
OS=Windows_NT
COMPUTERNAME=MPILGRIM
USERNAME=mpilgrim

You can read about tuple unpacking as mentioned by @iCodez. at Tuples in Python and Unpacking Tuples links, they explained it with proper examples.

a.m.
  • 2,083
  • 1
  • 16
  • 22