Python Forum

Full Version: slicing and indexing a list example
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have the following code:

s = "The quick brown fox jumps over the lazy dog."
words = s.split()
lengths = [[w.lower(), len(w)] for w in words]
for length in lengths:
 print(length)
The output is:

['the', 3]
['quick', 5]
['brown', 5]
['fox', 3]
['jumps', 5]
['over', 4]
etc.

I wish to change it to produce the lengths only, namely the numbers.
Also, is this an example of lists inside lists (nested lists)?
I am trying to
In your comprehension, you've asked the list to be assembled from [w.lower(), len(w)]. So the elements are: a list, with the lowercasename first, and the length second.

If you just want the lengths, just put the lengths there. Change the line to:

lengths = [len(w) for w in words]
But you should also pay attention to output of your code. Is 'dog' 4 letter word?
(Oct-01-2020, 02:12 AM)bowlofred Wrote: [ -> ]In your comprehension, you've asked the list to be assembled from [w.lower(), len(w)]. So the elements are: a list, with the lowercasename first, and the length second.

If you just want the lengths, just put the lengths there. Change the line to:

lengths = [len(w) for w in words]


Let me amend my question. I wanted to access every length inside each of the outputs.
How do I do this indexing since each output is a list containing 2 elements?
So I tried the following:
print(length[1:])
I'm afraid I can't understand exactly what you're asking. Can you show what you expect the output to be?