Python Forum
Help me understand a simple list comprehension
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help me understand a simple list comprehension
#2
Ah, yes, list comprehensions. They're a trip when you first learn about them.

The portion you're referencing is equivalent to:

out = []
for i in [2, 4, 6]:
    out.append(list(range(i, i + 3)))
It will loop over the list [2, 4, 6] assigning the variable "i" to the value of the current iteration each time. So, the first time through, i = 2; the second time, i = 4; etc.

The range() function returns an iterator starting at the first value provided and incrementing to the second value. So, range(i, i + 3) will start at "i" and end at "i + 3". For the first iteration of the loop, i = 2 and the call will be for range(2, 5), which can be used to produce the list [2, 3, 4].

In short, the first part of the list comprehension instructs the interpreter what to add to the list while the second part provides a loop expression to direct the process. Each time the loop iterates, it appends a new range() to the list. However, list comprehensions are faster than the equivalent code I wrote above.

To accomplish this without numpy:

[list(range(i, i + 3)) for i in [2, 4, 6]]
Reply


Messages In This Thread
RE: Help me understand a simple list comprehension - by stullis - Oct-17-2018, 03:19 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  List comprehension: paul18fr 1 1,437 Oct-29-2021, 05:36 PM
Last Post: Yoriz
  list comprehension invalid syntax mcgrim 1 4,786 Jun-12-2019, 08:28 PM
Last Post: Yoriz
  Python List Comprehension. rinu 3 3,134 Jan-08-2019, 12:30 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

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