Python Forum
List Comprehension - Creating a list of the length of an item help
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List Comprehension - Creating a list of the length of an item help
#1
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.
Reply
#2
Do you mean this?
Newlist = [len(item[1]) for item in file]
Reply
#3
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'
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  List Comprehension Issue johnywhy 5 438 Jan-14-2024, 07:58 AM
Last Post: Pedroski55
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 426 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  No matter what I do I get back "List indices must be integers or slices, not list" Radical 4 1,091 Sep-24-2023, 05:03 AM
Last Post: deanhystad
  Delete strings from a list to create a new only number list Dvdscot 8 1,466 May-01-2023, 09:06 PM
Last Post: deanhystad
  Using list comprehension with 'yield' in function tester_V 5 1,175 Apr-02-2023, 06:31 PM
Last Post: tester_V
  List all possibilities of a nested-list by flattened lists sparkt 1 878 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Сheck if an element from a list is in another list that contains a namedtuple elnk 8 1,713 Oct-26-2022, 04:03 PM
Last Post: deanhystad
  Creating list of lists, with objects from lists sgrinderud 7 1,561 Oct-01-2022, 07:15 PM
Last Post: Skaperen
Question Keyword to build list from list of objects? pfdjhfuys 3 1,499 Aug-06-2022, 11:39 PM
Last Post: Pedroski55
  list comprehension 3lnyn0 4 1,359 Jul-12-2022, 09:49 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020