Since an OrderedDict has the features of both a list (with ordered elements), and a dictionary (with keys instead of indexes), it would seem natural that you could slice using keys. What’s interesting about this is that it’s not the error you’d see due to OrderedDictionary.__getslice__ not being implemented. I tried adding my own __getslice__ method to OrderedDict, but I
Tag: python-internals
Do attribute names consume memory on instance basis in python
Considering I have millions of objects with 3 __slots__ Is it more memory efficient to have short slot names like x vs. long like would_you_like_fries_with_that_cheeseburger? Or are the names allocated only once per class (opposed to once per instance?) Answer Names for slots only take memory per class, not per instance. Slots use descriptors that map directly into the memory
Randomly extract x items from a list using python
Starting with two lists such as: I want to have the user input how many items they want to extract, as a percentage of the overall list length, and the same indices from each list to be randomly extracted. For example say I wanted 50% the output would be I have achieved this using the following code: But I was
Why does a set display in same order if sets are unordered?
I’m taking a first look at the python language from Python wikibook. For sets the following is mentioned: We can also have a loop move over each of the items in a set. However, since sets are unordered, it is undefined which order the iteration will follow. and the code example given is : Output: When I run the program
Why is Python’s ‘len’ function faster than the __len__ method?
In Python, len is a function to get the length of a collection by calling an object’s __len__ method: So I would expect direct call of __len__() to be at least as fast as len(). Demo link But results of testing with the above code shows len() to be faster. Why? Answer The builtin len() function does not look up
How does the @property decorator work in Python?
I would like to understand how the built-in function property works. What confuses me is that property can also be used as a decorator, but it only takes arguments when used as a built-in function and not when used as a decorator. This example is from the documentation: property’s arguments are getx, setx, delx and a doc string. In the