P
Player
Hi all
I am teaching myself python and so am following a few tutorials from
online.
In one of the tutorials an exercise is the following...
As an exercise, write a loop that traverses the previous list and prints
the length of each element.
Firstly I just wanted to see if I could get the length out of those elements
that were list type.
I no thats not exactly what the exercise asks for, but I thought I would
start there.
However I am stuck and cant figure out why my code is doing what it's doing.
My code is as follows....
mylist = [1, 2, ["three", "four"], "five"]
for item in mylist:
if item == type(list):
myitem = len(item)
print myitem
else:
print item
All my code seems to do is print out each element of the list on a new line.
What I had expected it to do was this....
1
2
2
'five'
but it doesn't, what it does do is this...
1
2
['three', 'four']
'five'
I expected the line,
myitem = len(item)
to issue the variable, myitem, with a value that was the length of item.
But as you cans ee it doesn't and simply ignores all that code and does the
else:
print item
part instead, misisng out the first half of the for loop.
Were am I going wrong ??
Thanks in advance for any help
M.B aka - Player -
--
*************
The Imagination may be compared to Adam's dream-
he awoke and found it truth.
John Keats.
*************
I am teaching myself python and so am following a few tutorials from
online.
In one of the tutorials an exercise is the following...
As an exercise, write a loop that traverses the previous list and prints
the length of each element.
Firstly I just wanted to see if I could get the length out of those elements
that were list type.
I no thats not exactly what the exercise asks for, but I thought I would
start there.
However I am stuck and cant figure out why my code is doing what it's doing.
My code is as follows....
mylist = [1, 2, ["three", "four"], "five"]
for item in mylist:
if item == type(list):
myitem = len(item)
print myitem
else:
print item
All my code seems to do is print out each element of the list on a new line.
What I had expected it to do was this....
1
2
2
'five'
but it doesn't, what it does do is this...
1
2
['three', 'four']
'five'
I expected the line,
myitem = len(item)
to issue the variable, myitem, with a value that was the length of item.
But as you cans ee it doesn't and simply ignores all that code and does the
else:
print item
part instead, misisng out the first half of the for loop.
Were am I going wrong ??
Thanks in advance for any help
M.B aka - Player -
--
*************
The Imagination may be compared to Adam's dream-
he awoke and found it truth.
John Keats.
*************