Python Forum
List Comprehension - Creating a list of the length of an item help - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: List Comprehension - Creating a list of the length of an item help (/thread-22532.html)



List Comprehension - Creating a list of the length of an item help - paul41 - Nov-16-2019

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.


RE: List Comprehension - Creating a list of the length of an item help - ibreeden - Nov-17-2019

Do you mean this?
Newlist = [len(item[1]) for item in file]



RE: List Comprehension - Creating a list of the length of an item help - perfringo - Nov-18-2019

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'