round and square brackets (parenthesis) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

round and square brackets (parenthesis)

Hi people, I'm kind of lost in the round and square brackets (parenthesis). can anybody tell me when do i use one or the other? Ex: nums= [3,4,5] or nums=(3,4,5) where is the difference in that?

28th Sep 2016, 8:27 AM
Andrei Giura
Andrei Giura - avatar
1 Answer
0
Hi, Square brackets are lists while parentheses are tuples. A list is mutable, meaning you can change its contents: >>> x = [1,2] >>> x.append(3) >>> x [1, 2, 3] while tuples are not: >>> x = (1,2) >>> x (1, 2) >>> x.append(3) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'tuple' object has no attribute 'append' The other main difference is that a tuple is hashable, meaning that you can use it as a key to a dictionary, among other things, you can add tuples together However, this does not mean tuples are mutable. When a new tuple is constructed by adding together the two tuples as arguments. The original tuple is not modified. more about lists: https://docs.python.org/3/tutorial/datastructures.html#more-on-lists more about tuples: https://www.tutorialspoint.com/python/python_tuples.htm A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
5th Oct 2016, 10:56 AM
Krasimir Vatchinsky
Krasimir Vatchinsky - avatar