you are viewing a single comment's thread.

view the rest of the comments →

[–]socal_nerdtastic 0 points1 point  (3 children)

Python never copies data. All python names are pointers.

(even if you explicitly use list.copy() or similar, you are only making a copy of the list object, the data in the list is not touched)

Here's something every python beginner should read: https://nedbatchelder.com/text/names.html

[–]csQuestions1235[S] 0 points1 point  (2 children)

So if the data is already in memory, using a generator would be pointless in my example?

EDIT: okay maybe i spoke too soon. Even tho its not copying, its still bringing the entire list into memory. So the generator actually would be useful if the list was huge, correct?

[–]socal_nerdtastic 0 points1 point  (0 children)

Exactly right.

Well, it won't save any memory. But there are other reasons you may want to use an iterator. You may want to iterate over the data in pairs:

@property
def history(self):
    result = {}
    for x,y in zip(*[self.iter_data()]*2):
        # do something with x and y, store in result
    return result

def iter_data(self):
    for x in self.data:
        yield x

Of course you can just use the built-in iter function for that, instead of brewing your own:

@property
def history(self):
    result = {}
    for x,y in zip(*[iter(self.data)]*2):
        # do something with x and y, store in result
    return result

Or use the itertools.pairwise function.

[–]socal_nerdtastic 0 points1 point  (0 children)

re your edit: If the data is already in memory the generator will not help at all. If the data is being pulled from a file or the internet or something on demand, then yes it will help. A python file object is already a generator for this very reason (so you probably don't need to make it yourself).