The Star (*) operator applies to lists and integers.

Let's say we have a class Fooand we want to create a list foosthat we can do as follows:

foo_list = [Foo()] * 3

Now, what if we do foo_list[0].x = 5? This statement sets the attribute xto all of the instances within the list !!!

When I found this, it blew my mind. The problem is that when we create such a list, it is obvious that python will first create an instance Foo, then an instance of the list, and then add the same object 3 times to it, but I really expected it to do something like this

foo_list = [Foo() for i in range(3)]

Is not it? Well, now I know that definitely this syntactic sugar cannot be used since I wanted to use it, but then what is it used for? The only thing I can think of is to create a list with an initial size like this: list = [None] * 5and that doesn't really matter much to me in the case of python.

Does this syntax have any other really useful use case?

+2
source share
3 answers

You can use a star shape with any type of immutable , such as

print [5] * 3
print "abc" * 3
print [1.1] * 3
print (8,) * 3

Let's say for example

nums = [5] * 3
print map(id, nums)

Exit on my car

[41266184, 41266184, 41266184]

id . , . . (, )

, ,

,

[Foo() for i in range(3)]

,

[5] * 3
+7

, .

foo_list = [Foo()] * 3

foo_list = ( [Foo()] ) * 3

foo_instance = Foo()
bar_list = [foo_instance]
foo_list = bar_list * 3

. , , , .

, , - , , n, n , slice:

def set_to_length(l, n, defaultvalue=0):
    return (l + [defaultvalue] * n)[:n]

, , .

0

:

list=[any_object]*n

- 1- . :

>>> l=[foo()]*3
>>> l
[<__main__.foo instance at 0x02D64D28>, <__main__.foo instance at 0x02D64D28>, <__main__.foo instance at 0x02D64D28>]
>>> m=[ foo() for i in range(3)]
>>> m
[<__main__.foo instance at 0x02D64F08>, <__main__.foo instance at 0x02D613A0>, <__main__.foo instance at 0x02D611C0>]

l

, id (),

m

they are different. The fact is that when you use list views, you are actually doing the process of creating three objects on the same line, rather than using a loop to create objects and place them in a list, but the first list=[any_object]*nis just one more time to add the same the very object in the list is the desired number of times.

0
source

Source: https://habr.com/ru/post/1530049/


All Articles