Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 List Comprehension - Creating a list of the length of an item help
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:

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'
baquerik likes this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  extract first and last 5 elements from given list and generate a new list. Raj_Kumar 1 80 Dec-07-2019, 05:03 PM
Last Post: ichabod801
  item = index position - list of list RavCOder 9 139 Dec-02-2019, 05:24 PM
Last Post: ThomasL
  Understanding list comprehension Drone4four 5 117 Nov-15-2019, 04:31 PM
Last Post: ichabod801
  Writing list as a file, then reading that file as a list Zoastria_Balnala 3 169 Oct-17-2019, 07:54 PM
Last Post: Zoastria_Balnala
  I created a function that generate a list but the list is empty in a new .py file mrhopeedu 2 141 Oct-12-2019, 08:02 PM
Last Post: mrhopeedu
  Simple list comprehension misunderstanding Mark17 3 218 Oct-10-2019, 07:00 PM
Last Post: buran
  Creating a list from a comprehension using a list rm197 6 181 Sep-30-2019, 07:02 PM
Last Post: rm197
  Converting List into list of tuples ARV 4 360 Sep-28-2019, 04:58 AM
Last Post: perfringo
  Assigning an item from a list xlev 1 138 Sep-27-2019, 04:42 PM
Last Post: Larz60+
  creating a list from lists of lists ridgerunnersjw 1 318 Sep-13-2019, 05:22 PM
Last Post: snippsat

Forum Jump:

Users browsing this thread: 1 Guest(s)