Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
654 views
in Technique[技术] by (71.8m points)

syntax - What is the difference between curly brace and square bracket in Python?

what is the difference between curly brace and square bracket in python?

A ={1,2}
B =[1,2]

when I print A and B on my terminal, they made no difference. Is it real?

And sometimes, I noticed some code use {} and [] to initialize different variables.

E.g. A=[], B={}

Is there any difference there?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Curly braces create dictionaries or sets. Square brackets create lists.

They are called literals; a set literal:

aset = {'foo', 'bar'}

or a dictionary literal:

adict = {'foo': 42, 'bar': 81}
empty_dict = {}

or a list literal:

alist = ['foo', 'bar', 'bar']
empty_list = []

To create an empty set, you can only use set().

Sets are collections of unique elements and you cannot order them. Lists are ordered sequences of elements, and values can be repeated. Dictionaries map keys to values, keys must be unique. Set and dictionary keys must meet other restrictions as well, so that Python can actually keep track of them efficiently and know they are and will remain unique.

There is also the tuple type, using a comma for 1 or more elements, with parenthesis being optional in many contexts:

atuple = ('foo', 'bar')
another_tuple = 'spam',
empty_tuple = ()
WARNING_not_a_tuple = ('eggs')

Note the comma in the another_tuple definition; it is that comma that makes it a tuple, not the parenthesis. WARNING_not_a_tuple is not a tuple, it has no comma. Without the parentheses all you have left is a string, instead.

See the data structures chapter of the Python tutorial for more details; lists are introduced in the introduction chapter.

Literals for containers such as these are also called displays and the syntax allows for procedural creation of the contents based of looping, called comprehensions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...