[Tutor] RE:

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Jan 18 08:17:34 CET 2005



> >  >>> stuff = [[0,'sdfsd','wrtew'], [1, 'rht','erterg']]
> >  >>> stuff
> > [[0, 'sdfsd', 'wrtew'], [1, 'rht', 'erterg']]
> >  >>> print [stuff[i][0] for i in range(len(stuff))]
> > [0, 1]
> >
> > An alternative way to write this is:
> >
> > ###
> > print [row[0] for row in stuff]
> > ###
> >
> > which extracts the first element out of every "row" sublist in
> > 'stuff'.


> This is fine.  I just want to know if row is a reserve word? or is it a
> built in function in IDLE environment.  The word row is not highlighted.
> What data type is (row)?


Hello!

When we have 'stuff' like this:

###
>>> stuff = [[0,'sdfsd','wrtew'], [1, 'rht','erterg']]
###

then we can ask for an element out of 'stuff'.  One thing we can do is
variable assignment:

###
>>> row = stuff[0]
###

'row' here is just an arbitrarily chosen variable name.  We can see that
"row"'s value is one of the sublists in 'stuff' by trying:

###
>>> print row
[0, 'sdfsd', 'wrtew']
###


We can also use a 'for' loop to march --- to "iterate" --- across a list:

###
>>> for row in stuff:
...     print row, "is another element in 'stuff'"
...
[0, 'sdfsd', 'wrtew'] is another element in 'stuff'
[1, 'rht', 'erterg'] is another element in 'stuff'
###

'row' here is also used as a temporary variable name.  In a 'for' loop, it
is assigned to each element, as we repeat the loop's body.


If you have more questions, please feel free to ask.



More information about the Tutor mailing list