Python Forum

Full Version: List Comprehension - Creating a list of the length of an item help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am working within a file which is within a for loop. Within this for loop i am wanting to create a new list. I can do what i want using normal list way but was hoping to find out how to convert this into list comprehension. The complication to this is i am wanting to get the length of 'y' within the for loop captured into the new list.

Working way (long way):
NewList = []

for (x, y) in file:
    NewList.append(len(y))

print(NewList     
The above gives me what I want. However, I am hoping to make this more elegant and turn this into list comprehension. Anyone any ideas?

I have tried:
Newlist = [item for item in len(y)]
However, this does not work :-(. Thanks in advance.
Do you mean this?
Newlist = [len(item[1]) for item in file]
If you want turn your first code into list comprehension one-to-one you just write:

[len(y) for (x, y) in file]
In list comprehension what you get/want comes first. In spoken language: 'give me length of y for every x, y in file'