general-purpose programming language
Python is a high-level, general-purpose programming language that emphasizes code readability, simplicity, and ease-of-writing with the use of significant indentation, an extensive ("batteries-included") standard library, and garbage collection. Python supports multiple programming … Wikipedia
🌐
Python
python.org
Welcome to Python.org
The official home of the Python Programming Language
🌐
Reddit
reddit.com β€Ί r β€Ί Python
r/Python
January 25, 2008 - This space is reserved for questions about more advanced Python topics, frameworks, and best practices.
Discussions

Whats the difference between (), [] and {}?
[] is a list, and is mutable, in that its size can vary. () is a tuple. Tuples are immutable, in that their sizes cannot vary. Immutable objects can be hashed, which is an important property. You can concatenate tuples, but it returns a new tuple, not the same one. Extending / appending to a list returns the same list object. {} is a set, in that it contains unique, immutable objects. {} is also used to create a dictionary, where the dictionary has a set of keys. For instance: a = [1, 1, 2, 3, 4] b = (1, 1, 2, 3, 4) c = {a} Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list' d = {b} print(d) {(1, 1, 2, 3, 4)} You'll notice that c throws an error, and d does not. This is because a is a list that is mutable and unhashable, while b is the immutable, hashable, tuple (1, 1, 2, 3, 4). The built-in set assumes an iterable, and produces the set of the values within the iterable, so if you want to know the set of the values in a: e = set(a) print(e) {1, 2, 3, 4} Similarly, the set of the values in b: f = set(b) print(f) {1, 2, 3, 4} Why use tuples then? What if you want to know the unique set of a list of tuples? g = [(1,2,3,4), (2,3,4,5), (1,2,3,4), (4,5,6,7), (2,3,4,5)] h = set(g) print(h) {(1, 2, 3, 4), (4, 5, 6, 7), (2, 3, 4, 5)} Here is a recent example of a real-life problem that was posted in this subreddit that was solved using this method. Only the unique tuples are returned. It is important to note that sets do not preserve order. There is an OrderedSet package available, but in general if you are using sets order usually doesn't matter. If you find yourself needing to keep the order, there is usually a better method to do what you want to achieve. Similarly, using a list of lists will fail: i = [[1,2,3,4], [2,3,4,5], [1,2,3,4], [4,5,6,7], [2,3,4,5]] j = set(i) Traceback (most recent call last): File "", line 2, in TypeError: unhashable type: 'list' More on reddit.com
🌐 r/learnpython
9
3
November 20, 2020
python - What's the difference between () vs [] vs {}? - Stack Overflow
What's the difference between () vs [] vs {} in Python? They're collections? How can I tell when to use which? More on stackoverflow.com
🌐 stackoverflow.com
python - What does ** (double star/asterisk) and * (star/asterisk) do for parameters? - Stack Overflow
What do *args and **kwargs mean in these function definitions? def foo(x, y, *args): pass def bar(x, y, **kwargs): pass See What do ** (double star/asterisk) and * (star/asterisk) mean in a More on stackoverflow.com
🌐 stackoverflow.com
What does asterisk * mean in Python? - Stack Overflow
Does * have a special meaning in Python as it does in C? I saw a function like this in the Python Cookbook: def get(self, *a, **kw) Would you please explain it to me or point out where I can find an More on stackoverflow.com
🌐 stackoverflow.com
🌐
Wikipedia
en.wikipedia.org β€Ί wiki β€Ί Python_(programming_language)
Python (programming language) - Wikipedia
1 day ago - Python is a high-level, general-purpose programming language that emphasizes code readability, simplicity, and ease-of-writing with the use of significant indentation, an extensive ("batteries-included") standard library, and garbage collection. Python supports multiple programming paradigms ...
🌐
Codecademy
codecademy.com β€Ί catalog β€Ί language β€Ί python
Best Python Courses + Tutorials | Codecademy
Python is a general-purpose, versatile, and powerful programming language. It's a great first language because Python code is concise and easy to read. Whatever you want to do, python can do it.
🌐
W3Schools
w3schools.com β€Ί python
Python Tutorial
Python Operators Arithmetic Operators Assignment Operators Ternary Operator Comparison Operators Logical Operators Identity Operators Membership Operators Bitwise Operators Operator Precedence Code Challenge Python Lists
🌐
Online Python
online-python.com
Online Python - IDE, Editor, Compiler, Interpreter
Python, which was initially developed by Guido van Rossum and made available to the public in 1991, is currently one of the most widely used general-purpose programming languages. Python's source code is freely available to the public, and its usage and distribution are unrestricted, including ...
Find elsewhere
🌐
Python
python.org β€Ί downloads
Download Python | Python.org
The official home of the Python Programming Language
🌐
W3Schools
w3schools.com β€Ί python β€Ί python_intro.asp
Introduction to Python
Python Operators Arithmetic Operators Assignment Operators Ternary Operator Comparison Operators Logical Operators Identity Operators Membership Operators Bitwise Operators Operator Precedence Code Challenge Python Lists
🌐
Programiz
programiz.com β€Ί python-programming β€Ί online-compiler
Online Python Compiler (Interpreter) - Programiz
# Online Python compiler (interpreter) to run Python online. # Write Python 3 code in this online editor and run it. print("Start small.
🌐
PyPI
pypi.org
PyPI Β· The Python Package Index
The Python Package Index (PyPI) is a repository of software for the Python programming language.
🌐
Google
developers.google.com β€Ί google for education β€Ί python
Google's Python Class | Python Education | Google for Developers
Google's Python Class is a free resource for individuals with some programming experience to learn Python.
🌐
Visual Studio Marketplace
marketplace.visualstudio.com β€Ί items
Python - Visual Studio Marketplace
Extension for Visual Studio Code - Python language support with extension access points for IntelliSense (Pylance), Debugging (Python Debugger), linting, formatting, refactoring, unit tests, and more.
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί whats the difference between (), [] and {}?
r/learnpython on Reddit: Whats the difference between (), [] and {}?
November 20, 2020 -

I cant seem to understand the difference between them. I know [] is used for lists but thats it. If someone could explain them in detail to a newbie like me, id greatly appreciate it.

Top answer
1 of 3
4
[] is a list, and is mutable, in that its size can vary. () is a tuple. Tuples are immutable, in that their sizes cannot vary. Immutable objects can be hashed, which is an important property. You can concatenate tuples, but it returns a new tuple, not the same one. Extending / appending to a list returns the same list object. {} is a set, in that it contains unique, immutable objects. {} is also used to create a dictionary, where the dictionary has a set of keys. For instance: a = [1, 1, 2, 3, 4] b = (1, 1, 2, 3, 4) c = {a} Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list' d = {b} print(d) {(1, 1, 2, 3, 4)} You'll notice that c throws an error, and d does not. This is because a is a list that is mutable and unhashable, while b is the immutable, hashable, tuple (1, 1, 2, 3, 4). The built-in set assumes an iterable, and produces the set of the values within the iterable, so if you want to know the set of the values in a: e = set(a) print(e) {1, 2, 3, 4} Similarly, the set of the values in b: f = set(b) print(f) {1, 2, 3, 4} Why use tuples then? What if you want to know the unique set of a list of tuples? g = [(1,2,3,4), (2,3,4,5), (1,2,3,4), (4,5,6,7), (2,3,4,5)] h = set(g) print(h) {(1, 2, 3, 4), (4, 5, 6, 7), (2, 3, 4, 5)} Here is a recent example of a real-life problem that was posted in this subreddit that was solved using this method. Only the unique tuples are returned. It is important to note that sets do not preserve order. There is an OrderedSet package available, but in general if you are using sets order usually doesn't matter. If you find yourself needing to keep the order, there is usually a better method to do what you want to achieve. Similarly, using a list of lists will fail: i = [[1,2,3,4], [2,3,4,5], [1,2,3,4], [4,5,6,7], [2,3,4,5]] j = set(i) Traceback (most recent call last): File "", line 2, in TypeError: unhashable type: 'list'
2 of 3
1
Sure. These are all built-in aggregate data structures in Python. They all allow you to group variables together with a single name, but they differe a bit in how they work, so they are useful for different situations. The () symbols indicate a tuple in python. The most important thing about a tuple is it cannot change after it is created (technically this is called immutability) Tuples are great if you want a memory-efficient way to store and retrieve data, but you cannot change a single element of the tuple, or add or delete an element from a tuple. Tuples are the closest thing to arrays in more traditional languages like C, but still have some technical differences. a = (1, 2, 3) print(a[0]) 1 a[0] = 5 TypeError: You can't do this The [] symbols indicate a list. Lists in python are extremely powerful and flexible. You can easily add members to a list (in the beginning, end, or middle), sort lists, and much more. So this is legal with a list: b = [1, 2, 3] print(b[0]) 1 b[0] = 100 b.append(4) Look in the python documentation for all the interesting things you can do with a list. It's incredibly powerful, but does require a bit more memory and is a bit slower than a tuple. For a beginner this will not matter much, but the difference gets noticable when you start working on efficiency-critical operations like game dev. So you can think of a list as a much more flexible cousin to the tuple. The {} symbol refers to a dictionary. Dictionaries are similar to lists because they are dynamic. You can change them after the fact. But the big difference is this: For tuples and lists, we use numeric indices to figure out what is in the element: a[1], b[0]. Dictionaries allow you to use other things (usually strings) as the indices. Here's a common example: >>> c = { ... "Indiana": "Indianapolis", ... "Florida": "Talahassee", ... "Texas": "Austin" ... } >>> print(c["Indiana"]) Indianapolis This is useful in a situation like this where there isn't a clear integer index (What's state # 1?) Instead a dictionary works with a key / value pair. Note that the order of items in a dictionary isn't necessarily guaranteed. This varies between Python implementations. All of these data structures are related, and all are iterable, which means you can use Python's wonderful for syntax to get each element. All of these would work with the examples above: for item in a: print(item) for item in b: print(item) for key in c: print(key) for key, value in c.items(): print (value, key) For all of these data structures, python allows you to use any data type, or even change the types within the structure. This is much more flexible than most languages, which limit their array-like structures to a single type. Hope this helps.
🌐
Learn Python
learnpython.org
Learn Python - Free Interactive Python Tutorial
learnpython.org is a free interactive Python tutorial for people who want to learn Python, fast.
🌐
Codecademy
codecademy.com β€Ί learn β€Ί learn-python
Learn Python 2 | Codecademy
Python is a general-purpose, versatile and popular programming language.
Rating: 4.3 ​ - ​ 7.72K votes
🌐
JetBrains
jetbrains.com β€Ί pycharm
PyCharm: The only Python IDE you need
June 2, 2021 - There is only one tool that I use day to day that fundamentally changes how I create and maintain apps in Python, and that's PyCharm. There is simply no other editor or IDE that understands the entire structure of my application like PyCharm does. People may have heard me go on and on about how I love PyCharm, but it's genuine.
Top answer
1 of 16
3348

The *args and **kwargs are common idioms to allow an arbitrary number of arguments to functions, as described in the section more on defining functions in the Python tutorial.

The *args will give you all positional arguments as a tuple:

def foo(*args):
    for a in args:
        print(a)        

foo(1)
# 1

foo(1, 2, 3)
# 1
# 2
# 3

The **kwargs will give you all keyword arguments as a dictionary:

def bar(**kwargs):
    for a in kwargs:
        print(a, kwargs[a])  

bar(name='one', age=27)
# name one
# age 27

Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:

def foo(kind, *args, bar=None, **kwargs):
    print(kind, args, bar, kwargs)

foo(123, 'a', 'b', apple='red')
# 123 ('a', 'b') None {'apple': 'red'}

It is also possible to use this the other way around:

def foo(a, b, c):
    print(a, b, c)

obj = {'b':10, 'c':'lee'}

foo(100, **obj)
# 100 10 lee

Another usage of the *l idiom is to unpack argument lists when calling a function.

def foo(bar, lee):
    print(bar, lee)

baz = [1, 2]

foo(*baz)
# 1 2

In Python 3 it is possible to use *l on the left side of an assignment (Extended Iterable Unpacking), though it gives a list instead of a tuple in this context:

first, *rest = [1, 2, 3, 4]
# first = 1
# rest = [2, 3, 4]

Also Python 3 adds a new semantic (refer PEP 3102):

def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
    pass

Such function accepts only 3 positional arguments, and everything after * can only be passed as keyword arguments.

Note:

A Python dict, semantically used for keyword argument passing, is arbitrarily ordered. However, in Python 3.6+, keyword arguments are guaranteed to remember insertion order. "The order of elements in **kwargs now corresponds to the order in which keyword arguments were passed to the function." - What’s New In Python 3.6. In fact, all dicts in CPython 3.6 will remember insertion order as an implementation detail, and this becomes standard in Python 3.7.

2 of 16
852

It's also worth noting that you can use * and ** when calling functions as well. This is a shortcut that allows you to pass multiple arguments to a function directly using either a list/tuple or a dictionary. For example, if you have the following function:

def foo(x,y,z):
    print("x=" + str(x))
    print("y=" + str(y))
    print("z=" + str(z))

You can do things like:

>>> mylist = [1,2,3]
>>> foo(*mylist)
x=1
y=2
z=3

>>> mydict = {'x':1,'y':2,'z':3}
>>> foo(**mydict)
x=1
y=2
z=3

>>> mytuple = (1, 2, 3)
>>> foo(*mytuple)
x=1
y=2
z=3

Note: The keys in mydict have to be named exactly like the parameters of function foo. Otherwise it will throw a TypeError:

>>> mydict = {'x':1,'y':2,'z':3,'badnews':9}
>>> foo(**mydict)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() got an unexpected keyword argument 'badnews'
Top answer
1 of 5
387

See Function Definitions in the Language Reference.

If the form *identifier is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form **identifier is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.

Also, see Function Calls.

Assuming that one knows what positional and keyword arguments are, here are some examples:

Example 1:

# Excess keyword argument (python 3) example:
def foo(a, b, c, **args):
    print("a = %s" % (a,))
    print("b = %s" % (b,))
    print("c = %s" % (c,))
    print(args)
    
foo(a="testa", d="excess", c="testc", b="testb", k="another_excess")

As you can see in the above example, we only have parameters a, b, c in the signature of the foo function. Since d and k are not present, they are put into the args dictionary. The output of the program is:

a = testa
b = testb
c = testc
{'k': 'another_excess', 'd': 'excess'}

Example 2:

# Excess positional argument (python 3) example:
def foo(a, b, c, *args):
    print("a = %s" % (a,))
    print("b = %s" % (b,))
    print("c = %s" % (c,))
    print(args)
        
foo("testa", "testb", "testc", "excess", "another_excess")

Here, since we're testing positional arguments, the excess ones have to be on the end, and *args packs them into a tuple, so the output of this program is:

a = testa
b = testb
c = testc
('excess', 'another_excess')

You can also unpack a dictionary or a tuple into arguments of a function:

def foo(a,b,c,**args):
    print("a=%s" % (a,))
    print("b=%s" % (b,))
    print("c=%s" % (c,))
    print("args=%s" % (args,))

argdict = dict(a="testa", b="testb", c="testc", excessarg="string")
foo(**argdict)

Prints:

a=testa
b=testb
c=testc
args={'excessarg': 'string'}

And

def foo(a,b,c,*args):
    print("a=%s" % (a,))
    print("b=%s" % (b,))
    print("c=%s" % (c,))
    print("args=%s" % (args,))

argtuple = ("testa","testb","testc","excess")
foo(*argtuple)

Prints:

a=testa
b=testb
c=testc
args=('excess',)
2 of 5
211

I only have one thing to add that wasn't clear from the other answers (for completeness's sake).

You may also use the stars when calling the function. For example, say you have code like this:

>>> def foo(*args):
...     print(args)
...
>>> l = [1,2,3,4,5]

You can pass the list l into foo like so...

>>> foo(*l)
(1, 2, 3, 4, 5)

You can do the same for dictionaries...

>>> def foo(**argd):
...     print(argd)
...
>>> d = {'a' : 'b', 'c' : 'd'}
>>> foo(**d)
{'a': 'b', 'c': 'd'}
🌐
YouTube
youtube.com β€Ί watch
Part 1: What is Python & Why Learn It? - Python for Beginners - YouTube
New to programming? This is the perfect starting point! In Part 1 of this Python for Beginners series, we break down exactly what Python is, why it's one of ...
Published Β  2 weeks ago