Python Forum
What is the difference between a generator and a list comprehension?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What is the difference between a generator and a list comprehension?
#1
I'm new to generators. Reuven Lerner describes them as "lazy lists"

This one assigns the letters of a string to alist a prescribed number of times.

But alist has no values.

Is this because the generator only makes the values when called by print(list(alist))??

What exactly is alist here? Is it like a function that can be called?

#! /usr/bin/python3
# simple generator

myString = 'generator'
n = len(myString)
max_times = 12
alist = (myString[x % n] for x in range(max_times))

# alist returns <generator object <genexpr> at 0x7fb489ca4ba0> in Idle
# print(alist) returns <generator object <genexpr> at 0x7fb489ca4ba0> in Idle

print(list(alist)) # returns ['g', 'e', 'n', 'e', 'r', 'a', 't', 'o', 'r', 'g', 'e', 'n']
If I use a list comprehension, I get a list:

alist2 = [myString[x%n] for x in range(max_times)]
Enter alist2 in Idle and I immediately get:

Quote:>>> alist2
['g', 'e', 'n', 'e', 'r', 'a', 't', 'o', 'r', 'g', 'e', 'n']
>>>

What is the difference between a generator and a list comprehension??

Maybe, the generator uses less memory, only works on demand??
Reply


Messages In This Thread
What is the difference between a generator and a list comprehension? - by Pedroski55 - Jan-02-2021, 01:00 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  difference between forms of input a list to function akbarza 6 1,158 Feb-21-2024, 08:02 PM
Last Post: bterwijn
  List Comprehension Issue johnywhy 5 632 Jan-14-2024, 07:58 AM
Last Post: Pedroski55
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 527 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  Using list comprehension with 'yield' in function tester_V 5 1,344 Apr-02-2023, 06:31 PM
Last Post: tester_V
  list comprehension 3lnyn0 4 1,489 Jul-12-2022, 09:49 AM
Last Post: DeaD_EyE
  set.difference of two list gives empty result wardancer84 4 1,574 Jun-14-2022, 01:36 PM
Last Post: wardancer84
  List comprehension used differently coder_sw99 3 1,783 Oct-03-2021, 04:12 PM
Last Post: coder_sw99
  How to invoke a function with return statement in list comprehension? maiya 4 2,947 Jul-17-2021, 04:30 PM
Last Post: maiya
  List comprehension and Lambda cametan 2 2,291 Jun-08-2021, 08:29 AM
Last Post: cametan
  For Loop with List Comprehension muzikman 25 6,930 Dec-18-2020, 10:45 PM
Last Post: muzikman

Forum Jump:

User Panel Messages

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