Python: What does using [] mean here?

What is the difference between these two statements in python?

var = foo.bar

and

var = [foo.bar]

I think it turns var into a list containing foo.bar, but I'm not sure. Also, if this is behavior, and foo.bar is already a list that you get in each case?

For example: if foo.bar = [1, 2], will I get this?

var = foo.bar #[1, 2]

and

var = [foo.bar] #[[1,2]] where [1,2] is the first element in a multidimensional list
+5
source share
4 answers

[] - an empty list.

[foo.bar]creates a new list ( []) with foo.baras the first element in the list, which can then be referenced by its index:

var = [foo.bar]
var[0] == foo.bar # returns True 

So, you guessed that your appointment foo.bar = [1,2]exactly matches.

, Python. :

>>> []
[]
>>> foobar = [1,2]
>>> foobar
[1, 2]
>>> [foobar]
[[1, 2]]
+14

, , , foo.bar.

foo.bar = [1,2], [[1,2]].

,

>> a=[]
>> a.append([1,2])
>> a[0] 
[1,2]
>> b=[[1,2]]
>> b[0]
[1,2]

,

>> class Foos:
>>   bar=[1,2]
>> foo=Foos()
>> foo.bar
[1,2]
>> a=[foo.bar]
>> a
[[1,2]]
>> a[0]
[1,2]
+3

, var , foo.bar, . , , foo.bar - , ?

  • , .

  • foo.bar , , .

    h[1] >>> l = [1, 2]
    h[1] >>> [l]
    [[1, 2]]
    h[3] >>> l[l][0]
    [1, 2]
    
+1

/ , foo.bar /.

0

All Articles