i thought I knew basically most of py, but still fiding new concepts, thank you!!
@xzex260910 сағат бұрын
I would rater that you talk about the slice object it selt s = slice(start,stop, step) and the magic method that let you define this behavior on other iterable data types or collections. but it was cool
@parasgaur185622 сағат бұрын
Is there any difference between mylist[::] and mylist? Like I know the result will be the same. But does these [::] return a different class/sub-class of it? Or is there anything else, like for example some very niche case where one would prefer using [::] instead of just simply the name?
@thomasgoodwin264822 сағат бұрын
As I understand it, it will be the same class, but mylist returns a direct reference to the object, while mylist[::] returns a new object that is a copy of the original. I have seen it used to enforce the return of copies of lists, rather than references to the original list as a matter of security. (return by value vs by reference).
@david-komi820 сағат бұрын
In some rare cases you would want to use mylist[::]. In summary, that instruction makes a shallow copy of the original list named mylist, so this all has to do with copies. If you define mylist, for example, like this: mylist = list(range(1, 11)) # this creates the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] And let's say you want a copy of that list, modify the copy but not the original, your first instinct might be to write something like: list_copy = mylist.copy() This creates something called a shallow copy, where, in some cases, changing one of the lists might change the other list, here's an example: mylist = [1, [1, 2], 3] list_copy = my_list.copy() list_copy[1][0] = 7 # here, the copy is modified print(mylist) # -> [1, [7, 2], 3] suddenly, the original changed too This is because the objects are duplicated but their inner objects are referenced instead of duplicated, this commonly happens with collections. mylist[::] is the old-school low-key inefficient and whacky way to do a shallow copy for lists and it's only useful for compatibility. To prevent the behavior mentioned before, you have to do a deep copy with the copy.deepcopy function from the copy module. In terms of instances, mylist[::] returns the exact same class as mylist, a list. So, they are different in some way, because modifying the top elements of the list doesn't affect the other list, but if you are working with, for example, nested lists, modifying one list could modify the other. It is okay to use a shallow copy if you're completely sure that the list does not contain collections or objects that have inner objects.
@thomasgoodwin264819 сағат бұрын
@@david-komi8 What he said!☝ Thanks for breaking it down right. 😉