Since python 3.6 (or 3.4 ? I don't remember) we can annotate a function. Ex:
def getVersion() - > str:
Now what happens when a function returns a tuple ? We can do that:
def func() - > tuple:
But if we know the tuple is a tuple of two integers ? I read here: How to annotate types of multiple return values? that we can do that:
def func() - > Tuple[int, int]
These can be used as types in annotations using [], each having a unique syntax.,These can be used as types in annotations and do not support [].,These are not used in annotations. They are building blocks for declaring types.,A generic version of dict. Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as Mapping.
def greeting(name: str) - > str:
return 'Hello ' + name
Vector = list[float] def scale(scalar: float, vector: Vector) - > Vector: return [scalar * num for num in vector ] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])
from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) - > None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) - > None: ...
from typing
import NewType
UserId = NewType('UserId', int)
some_id = UserId(524313)
def get_user_name(user_id: UserId) - > str: ... # typechecks user_a = get_user_name(UserId(42351)) # does not typecheck; an int is not a UserId user_b = get_user_name(-1)
# 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)
A tuple is immutable while a list is mutable.,Mutable and Immutable,Use a tuple if you don’t intend to mutable it.,As you can see clearly from the output, you can mutable a list. However, you cannot mutable a tuple. The following will result in an error:
The following example defines a list and modifies the first element:
.wp - block - code {
border: 0;
padding: 0;
}
.wp - block - code > div {
overflow: auto;
}
.shcb - language {
border: 0;
clip: rect(1 px, 1 px, 1 px, 1 px); -
webkit - clip - path: inset(50 % );
clip - path: inset(50 % );
height: 1 px;
margin: -1 px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1 px;
word - wrap: normal;
word - break: normal;
}
.hljs {
box - sizing: border - box;
}
.hljs.shcb - code - table {
display: table;
width: 100 % ;
}
.hljs.shcb - code - table > .shcb - loc {
color: inherit;
display: table - row;
width: 100 % ;
}
.hljs.shcb - code - table.shcb - loc > span {
display: table - cell;
}
.wp - block - code code.hljs: not(.shcb - wrap - lines) {
white - space: pre;
}
.wp - block - code code.hljs.shcb - wrap - lines {
white - space: pre - wrap;
}
.hljs.shcb - line - numbers {
border - spacing: 0;
counter - reset: line;
}
.hljs.shcb - line - numbers > .shcb - loc {
counter - increment: line;
}
.hljs.shcb - line - numbers.shcb - loc > span {
padding - left: 0.75 em;
}
.hljs.shcb - line - numbers.shcb - loc::before {
border - right: 1 px solid #ddd;
content: counter(line);
display: table - cell;
padding: 0 0.75 em;
text - align: right; -
webkit - user - select: none; -
moz - user - select: none; -
ms - user - select: none;
user - select: none;
white - space: nowrap;
width: 1 % ;
}
fruits = ['apple', 'orange', 'banana']
fruits[0] = 'strawberry'
print(fruits) Code language: PHP(php)
Output:
['strawberry', 'orange', 'banana'] Code language: JSON / JSON with Comments(json)
As you can see clearly from the output, you can mutable a list. However, you cannot mutable a tuple. The following will result in an error:
fruits = ('apple', 'orange', 'banana')
fruits[0] = 'strawberry'
Code language: JavaScript(javascript)
Python doesn’t you to change the element of a tuple. But you can reference a new tuple. For example:
fruits = ('apple', 'orange', 'banana')
fruits = ('strawberry', 'orange', 'banana') Code language: JavaScript(javascript)
If you examine the memory addresses of the tuple objects, you’ll see that the fruits
variable references a different memory address after the assignment:
fruits = ('apple', 'orange', 'banana')
print(hex(id(fruits)))
fruits = ('strawberry', 'orange', 'banana')
print(hex(id(fruits)))
Code language: PHP(php)
Syntax of list and tuple is slightly different. Lists are surrounded by square brackets [] and Tuples are surrounded by parenthesis ().,The literal syntax of tuples is shown by parentheses () whereas the literal syntax of lists is shown by square brackets [] .,Above, we defined a variable called list_num which hold a list of numbers from 1 to 4.The list is surrounded by brackets []. Also, we defined a variable tup_num; which contains a tuple of number from 1 to 4. The tuple is surrounded by parenthesis ().,Lists and Tuples are similar in most context but there are some differences which we are going to find in this article.
Example 1.1: Creating List vs. Creating Tuple
list_num = [1, 2, 3, 4] tup_num = (1, 2, 3, 4) print(list_num) print(tup_num)
Output:
[1, 2, 3, 4]
(1, 2, 3, 4)
Example 1.2: Find type of data structure using type() function
type(list_num) type(tup_num)
Example 3.1: List Directory
dir(list_num)
Example 3.2: Tuple Directory
dir(tup_num)
[('Swordfish', 'Dominic Sena', 2001), ('Snowden', ' Oliver Stone', 2016), ('Taxi Driver', 'Martin Scorsese', 1976)]
[(2, 4), (5, 7), (3, 8), (5, 9)]
[(2,4), (5,7), (3,8), (5,9)]
[ [2, 4], [5, 7], [3, 8], [5, 9] ]
January 3, 2022 19 min read 5429
When declaring a variable in statically-typed languages like C and Java, you are mandated to declare the data type of the variable. As a result, you cannot assign a value that does not conform to the data type you specified for the variable. For example, if you declare a variable to be an integer, you can’t assign a string value to it at any point in time.
int x = 4;
x = "hello"; // this would trigger a type error
In Python, you can define a variable with a type hint using the following syntax:
variable_name: type = value
Let’s look at the following variable:
name = "rocket”
In Python, you can read the type hints defined on variables using the __annotations__
dictionary:
>>> name: str = "rocket"
>>> __annotations__
{'name': <class 'str'>}
As mentioned earlier, the Python interpreter does not enforce types, so defining a variable with a wrong type won’t trigger an error:
>>> name: int = "rocket" >>>
tuple[...] is valid as a base class in Python 3.6 and later, and always in stub files. In earlier Python versions you can sometimes work around this limitation by using a named tuple as a base class (see section Named tuples).,PEP 604 introduced an alternative way for spelling union types. In Python 3.10 and later, you can write Union[int, str] as int | str. It is possible to use this syntax in versions of Python where it isn’t supported by the runtime with some limitations (see Annotation issues at runtime).,Sometimes you may want to write a function which will accept only unicode strings. This can be challenging to do in a codebase intended to run in both Python 2 and Python 3 since str means something different in both versions and unicode is not a keyword in Python 3.,Python 3.6 introduced an alternative, class-based syntax for named tuples with types:
class A:
def f(self) - > int: # Type of self inferred(A)
return 2
class B(A):
def f(self) - > int:
return 3
def g(self) - > int:
return 4
def foo(a: A) - > None:
print(a.f()) # 3
a.g() # Error: "A"
has no attribute "g"
foo(B()) # OK(B is a subclass of A)
a: Any = None
s: str = ''
a = 2 # OK(assign "int"
to "Any")
s = a # OK(assign "Any"
to "str")
def show_heading(s) - > None: print('=== ' + s + ' ===') # No static type checking, as s has type Any show_heading(1) # OK(runtime error only; mypy won 't generate an error)
def wait(t: float): # Implicit Any return value print('Waiting...') time.sleep(t) if wait(2) > 1: # Mypy doesn 't catch this error! ...
def wait(t: float) - > None: print('Waiting...') time.sleep(t) if wait(2) > 1: # Error: can 't compare None and int ...
# Use `typing.Tuple` in Python 3.8 and earlier
def f(t: tuple[int, str]) - > None:
t = 1, 'foo'
# OK
t = 'foo', 1 # Type check error
Last Updated : 25 Jul, 2022
Syntax of List
list_data = ['an', 'example', 'of', 'a', 'list']
Syntax of Tuple
tuple_data = ('this', 'is', 'an', 'example', 'of', 'tuple')
Output:
Original list[1, 2, 4, 4, 3, 3, 3, 6, 5]
Example to show mutablity[1, 2, 4, 77, 3, 3, 3, 6, 5]
An important difference between a list and a tuple is that lists are mutable, whereas tuples are immutable. What exactly does this imply? It means a list's items can be changed or modified, whereas a tuple's items cannot be changed or modified.,In most cases, lists and tuples are equivalent. However, there are some important differences to be explored in this article.,Let's consider the example highlighting the difference between lists and tuples in immutability and mutability.,This tutorial will study the major differences between lists and tuples and how to handle these two data structures.
List is: [4, 5, 7, 1, 7] Tuple is: (4, 1, 8, 3, 9)
<class 'list'>
<class 'tuple'>
['Python', 'Lists', 'Tuples', 'Mutable']
Tuples cannot be modified because they are immutable
Size of tuple: 28 Size of list: 52
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
Tuples: - are immutable i.e. we can not update a tuple. - generally are heterogeneous data structure. - is a sequence where position have semantic value. - are more like records, collection of fixed number of fields.,List:- are mutable i.e. we can add, extend or update a list.- generally are homogeneous data structures.,- is just like mathematical set.- is unordered.- is mutable.- doesn't contain duplicate values.,Shallow copy: Shallow copy creates a new object and then use the reference to refer the inner objects.
>>> [x for x in range(10) ] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
import time
>>>
time.localtime()
time.struct_time(tm_year = 2017, tm_mon = 9, tm_mday = 25, tm_hour = 21, tm_min = 52, tm_sec = 24, tm_wday = 0, tm_yday = 268, tm_isdst = 0)
- is just like mathematical set.
- is unordered.
- is mutable.
- doesn't contain duplicate values.
rana @Brahma: ~$ python3
Python 3.5 .2(
default, Nov 23 2017, 16: 37: 01)[GCC 5.4 .0 20160609] on linux
Type "help", "copyright", "credits"
or "license"
for more information. >>>
mylist = [1, 2, 5, 2, 3] >>>
a = set(mylist) >>>
a {
1,
2,
3,
5
}
input():
- In python2, input()
tries to run the user input as a valid python expression.
rana @Brahma: ~$ python2
Python 2.7 .12(
default, Nov 19 2016, 06: 48: 10)[GCC 5.4 .0 20160609] on linux2
Type "help", "copyright", "credits"
or "license"
for more information. >>>
input()
2 ^ 3
1
>>>
input(2 ** 3)
8
Shallow copy:
Shallow copy creates a new object and then use the reference to refer the inner objects.
>>> a = [ [1, 2], [3, 4] ] >>> b = a.copy() >>> print(id(a) == id(b)) False >>> print(id(a[0]) == id(b[0])) True