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

后端 未结 4 1221
谎友^
谎友^ 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 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]
    

提交回复
热议问题