Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between () vs [] vs {}?

What's the difference between () vs [] vs {} in Python?
They're collections? How can I tell when to use which?

like image 560
Zolomon Avatar asked Dec 10 '10 10:12

Zolomon


People also ask

What is [] used for in Python?

[] (Index brackets) Index brackets ([]) have many uses in Python. First, they are used to define "list literals," allowing you to declare a list and its contents in your program. Index brackets are also used to write expressions that evaluate to a single item within a list, or a single character in a string.

What is the difference between parentheses and brackets in Python?

What is the difference between parentheses (), brackets [], and braces {} in a python code? Brackets are used to make lists Braces are used to make dictionary Parenthesis are used to make tuple But for indexing in all of those, only brackets are used.

What is the difference between square brackets and round brackets in Python?

square bracket is used for indexing an array/list/dict, round brackets are used in function calls.

What is the difference between and JavaScript?

No difference in JavaScript. The only requisite is that the last quotation mark matches the first quotation mark. In other languages they may have different applications but in JavaScript they are exactly the same.


2 Answers

() - tuple

A tuple is a sequence of items that can't be changed (immutable).

[] - list

A list is a sequence of items that can be changed (mutable).

{} - dictionary or set

A dictionary is a list of key-value pairs, with unique keys (mutable). From Python 2.7/3.1, {} can also represent a set of unique values (mutable).

like image 73
Greg Hewgill Avatar answered Sep 30 '22 22:09

Greg Hewgill


  • () is a tuple: An immutable collection of values, usually (but not necessarily) of different types.
  • [] is a list: A mutable collection of values, usually (but not necessarily) of the same type.
  • {} is a dict: Use a dictionary for key value pairs.

For the difference between lists and tuples see here. See also:

  • Python Tuples are Not Just Constant Lists
like image 41
Mark Byers Avatar answered Oct 01 '22 00:10

Mark Byers