Python: What does the use of [] mean here?

后端 未结 4 1188
谎友^
谎友^ 2021-01-18 19:21

What is the difference in these two statements in python?

var = foo.bar

and

var = [foo.bar]

I think it i

相关标签:
4条回答
  • 2021-01-18 19:57

    I think it is making var into a list containing foo.bar but I am unsure. Also if this is the behavior and foo.bar is already a list what do you get in each case?

    • Yes, it creates a new list.

    • If foo.bar is already a list, it will simply become a list, containing one list.

      h[1] >>> l = [1, 2]
      h[1] >>> [l]
      [[1, 2]]
      h[3] >>> l[l][0]
      [1, 2]
      
    0 讨论(0)
  • 2021-01-18 20:01

    [] is an empty list.

    [foo.bar] is creating a new list ([]) with foo.bar as the first item in the list, which can then be referenced by its index:

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

    So your guess that your assignment of foo.bar = [1,2] is exactly right.

    If you haven't already, I recommend playing around with this kind of thing in the Python interactive interpreter. It makes it pretty easy:

    >>> []
    []
    >>> foobar = [1,2]
    >>> foobar
    [1, 2]
    >>> [foobar]
    [[1, 2]]
    
    0 讨论(0)
  • 2021-01-18 20:02

    That pretty much means it's an array/list of stuff with foo.bar being the first item in the list/array.

    0 讨论(0)
  • 2021-01-18 20:09

    Yes, it's making a list containing one element, foo.bar.

    If foo.bar is [1,2], you indeed get [[1,2]].

    For instance,

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

    To elaborate a bit more on that exact example,

    >> class Foos:
    >>   bar=[1,2]
    >> foo=Foos()
    >> foo.bar
    [1,2]
    >> a=[foo.bar]
    >> a
    [[1,2]]
    >> a[0]
    [1,2]
    
    0 讨论(0)
提交回复
热议问题