Python Forum
convert list compression to for loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
convert list compression to for loop
#5
This reply speaks to your understanding of list comprehensions, so that you might understand the code,
and see there is probably no need to convert it.

This code:

    text = [y.text for x in player_data for y in x.descendants if y.name == 'div']
is equivalent to:

    text = []
    for x in player_data:
        for y in x.descendants:
            if y.name == 'div':
                text += [y.text]
As you can see the list comprehension is more concise, and, according to python developers,
executes more efficiently than the corresponding for loops. If the original code works,
and you change it, you risk breaking it without being able to fix it.
Reply


Messages In This Thread
RE: convert list compression to for loop - by miltmobley - Oct-09-2017, 09:40 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  convert set to a list type in python firaki12345 2 1,788 Feb-05-2021, 03:45 PM
Last Post: buran
  how to edit data frames and convert to a list(pandas, read_html()) ? donvirte 3 4,405 Feb-02-2018, 03:23 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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