Listing All (67) Python Built In Functions


Python has many functions that are built-in to the language, which means you don't need to write them yourself or import them.

Python built-in functions are used to perform a specific task on strings, lists, dictionaries, tuples, sets, and other objects.

These functions discussed in this article are available in Python3.

python built-in functions

This list of built-in functions available in this article is as follows:

  1. abs()
  2. all()
  3. any()
  4. ascii()
  5. bin()
  6. bool()
  7. bytearray()
  8. bytes()
  9. callable()
  10. chr()
  11. classmethod()
  12. compile()
  13. complex()
  14. delattr()
  15. dict()
  16. dir()
  17. divmod()
  18. enumerate()
  19. eval()
  20. exec()
  21. filter()
  22. float()
  23. format()
  24. frozenset()
  25. getattr()
  26. globals()
  27. hasattr()
  28. hash()
  29. help()
  30. hex()
  31. id()
  32. input()
  33. int()
  34. isinstance()
  35. issubclass()
  36. iter()
  37. len()
  38. list()
  39. locals()
  40. map()
  41. max()
  42. memoryview()
  43. min()
  44. next()
  45. object()
  46. oct()
  47. open()
  48. ord()
  49. pow()
  50. print()
  51. property()
  52. range()
  53. repr()
  54. reversed()
  55. round()
  56. set()
  57. setattr()
  58. slice()
  59. sorted()
  60. staticmethod()
  61. str()
  62. sum()
  63. super()
  64. tuple()
  65. type()
  66. vars()
  67. zip()

1. Python abs() Function

The abs() function returns the absolute value of a number. It turns a negative number into a positive number

It takes a single argument, a number, and returns the absolute value of that number.

The argument can be an integer or a floating point number.

a = abs(-10)
print(a) # 10

print(abs(5/3)) # 1.6666666666666667
print(abs(5.4)) # 5.4
print(abs(-5.4)) # 5.4

Output:

10
1.6666666666666667
5.4
5.4

2. Python all() Function

The all() function checks if all the elements of a sequence are true or if the sequence is empty. If yes then it returns True otherwise False.

It takes a single argument, a sequence, and returns True if all the elements of the sequence are true (or if the sequence is empty).

num = [1, 2, 3, 4, 5]
print(all(num)) # True

# change one number to 0
# boolean value of 0 is False
num[3] = 0
print(all(num)) # False

# check for an empty list
num = []
print(all(num)) # True

Output:

True
False
True

3. Python any() Function

The any() function returns True if any of the elements of a sequence is true or the sequence is empty. If no element is true then it returns False.

If any of the elements has a boolean value of True then the function returns True otherwise False.

num = [False, 0, '']
print(any(num)) # False

# change one number to 1
# boolean value of 1 is True
num[2] = 1
print(any(num)) # True

# check for an empty list
num = []
print(any(num)) # False

Output:

False
True
False

4. Python ascii() Function

The ascii() function returns a string containing a printable representation of an object. It escapes the non-ASCII characters in the string using \x, \u, or \U escapes.

It takes a single argument, an object, and returns a string containing a printable representation of the object.

a = '✋'

print(ascii(a))

print(ascii('å'))
print(ascii('🍟'))

Output:

'\u270b'
'\xe5'
'\U0001f35f'

5. Python bin() Function

The bin() function converts an integer into a binary number.

The function takes only integer values as an argument. Both positive and negative integers are accepted.

print(bin(1))
print(bin(5))
print(bin(9))
print(bin(-1))
print(bin(-4))

Output:

0b1
0b101
0b1001
-0b1

6. Python bool() Function

Every data type has a boolean value means it can be represented as True or False.

The bool() function converts any data type into its boolean value. Example 0, False, [], (), {}, '', None, are all converted into False whereas any other data type will be converted into True.

print(bool(0))
print(bool(False))
print(bool([]))
print(bool(()))
print(bool({}))
print(bool(''))
print(bool(None))

print(bool(1))
print(bool(True))
print(bool([1, 2, 3]))

Output:

False
False
False
False
False
False
False
True
True
True

7. Python bytearray() Function

The bytearray() function returns an array of bytes. It takes two parameters, the first is the source of bytes and the second is the encoding.

The source can be a string, a range, or a number. If the source is a string, the encoding must be specified.

print(bytearray(5))
print(bytearray('Python', 'utf-8'))
print(bytearray('Python', 'utf-16'))
print(bytearray(range(5)))

Output:

bytearray(b'\x00\x00\x00\x00\x00')
bytearray(b'Python')
bytearray(b'\xff\xfeP\x00y\x00t\x00h\x00o\x00n\x00')
bytearray(b'\x00\x01\x02\x03\x04')

8. Python bytes() Function

The bytes() function is used to create an immutable byte object from a string, a bytes-like object, or any object that implements the buffer protocol.

Whereas the bytearray() function returns a mutable bytes object.

print(bytes(5))
print(bytes('Python', 'utf-8'))
print(bytes('Python', 'utf-16'))
print(bytes(range(5)))

Output:

b'\x00\x00\x00\x00\x00'
b'Python'
b'\xff\xfeP\x00y\x00t\x00h\x00o\x00n\x00'
b'\x00\x01\x02\x03\x04'

9. Python callable() Function

The callable() function returns True if the object passed appears callable. If not, it returns False.

It takes a single argument, an object, and returns True if the object appears callable, otherwise, it returns False.

def func():
      print('Hello World')

print(callable(func)) # True
print(callable(1)) # False

Output:

True
False

10. Python chr() Function

The chr() function returns a string representing a character whose Unicode code point is the given integer.

It takes a single argument, an integer, and returns a string.

print(chr(65))
print(chr(97))
print(chr(1200))

Output:

A
a
Ұ

11. Python classmethod() Function

The classmethod() function returns a class method for a given function.

It transforms a function into a class method. A class method receives the class as an implicit first argument, just like an instance method receives the instance.

It takes a single argument, a function, and returns a class method for that function.

from datetime import date

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def fromBirthYear(cls, name, year):
        return cls(name, date.today().year - year)

    def display(self):
        print(self.name + '\'s age is: ' + str(self.age))

person1 = Person('John', 23)
person1.display()

person2 = Person.fromBirthYear('John', 1996)
person2.display()

Output:

John's age is: 23
John's age is: 26

12. Python compile() Function

The compile() function compiles the specified source as an object and returns it, ready to be executed.

It takes three arguments, the first is the source, the second is the filename, and the third is the mode.

The mode can be exec or eval.

code = compile('print("Hello World")', 'test.py', 'exec')
exec(code)

Output:

Hello World

13. Python complex() Function

The complex() function returns a complex number with the value real + imag*1j or converts a string or number to a complex number.

If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter.

It takes two arguments, the first is the real part, and the second is the imaginary part.

print(complex(2, 3))
print(complex(2))
print(complex('2+3j'))

Output:

(2+3j)
(2+0j)
(2+3j)

14. Python delattr() Function

The delattr() function deletes the named attribute from the given object.

It takes two arguments, the first is the object, and the second is the name of the attribute.

class Person:
    name = 'John'
    age = 23

person = Person()
print(person.name)

delattr(Person, 'name')
print(person.name)

Output:

John
AttributeError: 'Person' object has no attribute 'name'

15. Python dict() Function

The dict() function creates a dictionary.

If no parameters are passed, it returns an empty dictionary.

It takes two arguments, the first is the sequence of keys, and the second is the sequence of values.

print(dict())
print(dict(a='1', b='2', c='3'))
print(dict(zip(['a', 'b', 'c'], '123')))
print(dict([('a', '1'), ('b', '2'), ('c', '3')]))

Output:

{}
{'a': '1', 'b': '2', 'c': '3'}
{'a': '1', 'b': '2', 'c': '3'}
{'a': '1', 'b': '2', 'c': '3'}

16. Python dir() Function

The dir() function returns a list of valid attributes for the given object.

If the object has the __dir__() method, the method will be called and must return the list of attributes.

import datetime

print(dir())
print(dir(datetime))

Output:

['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'datetime']
['MAXYEAR', 'MINYEAR', '__doc__', '__name__', '__package__', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'tzinfo']

17. Python divmod() Function

The divmod() function takes two numbers and returns a pair of numbers (a tuple) consisting of their quotient and remainder.

It takes two arguments, the first is the dividend, and the second is the divisor.

print(divmod(7, 2))
print(divmod(8, 2))

Output:

(3, 1)
(4, 0)

18. Python enumerate() Function

The enumerate() function takes a collection (e.g. a tuple) and returns it as an enumerate object.

enumerate objects are iterables, typically used in for loop in Python.

It takes two arguments, the first is the sequence, and the second is the start index.

seasons = ['Spring', 'Summer', 'Fall', 'Winter']

print(list(enumerate(seasons)))
print(list(enumerate(seasons, start=1)))

Output:

[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

19. Python eval() Function

The eval() function runs the Python expression (code) within the program.

It takes one argument, the expression to be evaluated.

print(eval('1 + 2'))
print(eval('print("Hello World")'))
print(eval('len("Hello World")'))

Output:

3
Hello World
11

20. Python exec() Function

The exec() function executes the dynamically created program, which is either a string or a code object.

If the first argument is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs).

It takes two arguments, the first is the object to be executed, and the second is the globals and locals.

exec('print("Hello World")')

Output:

Hello World

21. Python filter() Function

The filter() function constructs an iterator from elements of an iterable for which a function returns true.

It takes two arguments, the first is the function, and the second is iterable.

def is_even(x):
    return x % 2 == 0

print(list(filter(is_even, range(10))))

Output:

[0, 2, 4, 6, 8]

22. Python float() Function

The float() function converts the specified value into a floating point number.

If no parameters are passed, it returns 0.0.

print(float())
print(float('1'))
print(float(1))
print(float(1.0))

Output:

0.0
1.0
1.0
1.0

23. Python format() Function

The format() is a string method that formats the given string into a nicer output in Python.

It is called on a string, takes an unlimited number of arguments, and returns the formatted string.

print('Hello, {}!'.format('World'))
print('Hello, {0}!'.format('World'))
print('Hello, {name}!'.format(name='World'))

Output:

Hello, World!
Hello, World!
Hello, World!

24. Python frozenset() Function

The frozenset() function returns an immutable frozenset object initialized with elements from the given iterable.

Property of frozenset object:

If no parameters are passed, it returns an empty frozenset.

print(frozenset())
print(frozenset('Book'))
print(frozenset(['B', 'o', 'o', 'k']))
print(frozenset(('B', 'o', 'o', 'k')))
print(frozenset({'B': 1, 'o': 2, 'k': 3}))

Output:

frozenset()
frozenset({'B', 'o', 'k'})
frozenset({'B', 'o', 'k'})
frozenset({'B', 'o', 'k'})
frozenset({'B', 'o', 'k'})

25. Python getattr() Function

The getattr() function returns the value of the named attribute of an object.

If not found, it returns the default value provided to the function.

It takes three arguments, the first is the object, the second is the name of the attribute, and the third is the default value.

class Person:
    name = 'John'
    age = 36
    
    def myfunc(self):
        print('Hello my name is ' + self.name)

p1 = Person()

print(getattr(p1, 'age'))
print(getattr(p1, 'name'))
print(getattr(p1, 'myfunc')())

Output:

36
John
Hello my name is John
None

26. Python globals() Function

The globals() function returns the dictionary of the current global symbol table.

It takes no arguments.

print(globals())

27. Python hasattr() Function

The hasattr() function returns true if the specified object has the specified attribute (named by the string), otherwise, it returns false.

It takes two arguments, the first is the object, and the second is the name of the attribute.

class Person:
    name = 'John'
    age = 36

p1 = Person()

print(hasattr(p1, 'age'))
print(hasattr(p1, 'name'))
print(hasattr(p1, 'id'))

Output:

True
True
False

28. Python hash() Function

The hash() function returns the hash value of the specified object.

hash value is an integer that is used to compare dictionary keys during a dictionary lookup quickly.

It takes one argument, the object to be hashed.


29. Python help() Function

The help() function invokes the built-in help system.

If no argument is given, it starts an interactive help session.

If the argument is a string, it is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console.

If the argument is any other kind of object, a help page on the object is generated.

help()

30. Python hex() Function

The hex() function converts an integer number to a lowercase hexadecimal string prefixed with "0x".

It takes one argument, the integer to be converted.

print(hex(8))
print(hex(10))
print(hex(255))
print(hex(-42))

Output:

0x8
0xa
0xff
-0x2a

31. Python id() Function

The id() function returns the "identity" of an object.

This is an integer that is guaranteed to be unique and constant for this object during its lifetime.

Two objects with non-overlapping lifetimes may have the same id() value.


32. Python input() Function

The input() function reads a line from the input, converts it to a string (stripping a trailing newline), and returns that.

If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.

If the optional argument prompt is present, it is written to standard output without a trailing newline.

name = input('Enter your name: ')

print('Hello ' + name)

Output:

Enter your name: John
Hello John

33. Python int() Function

The int() function is used to convert a value to an integer.

The passed value can be a string, a floating-point number, a boolean value, etc.

print(int('10'))
print(int(10.5))
print(int(True))

Output:

10
10
1

34. Python isinstance() Function

The isinstance() function returns true if the specified object is of the specified type, otherwise, it returns false.

It takes two arguments, the first is the object, and the second is the type.

class Person:
    name = 'John'
    age = 36

p1 = Person()

print(isinstance(p1, Person))

Output:

True

35. Python issubclass() Function

The issubclass() function returns true if the specified object is a subclass of the specified object, otherwise, it returns false.

It takes two arguments, the first is the object, and the second is the class.

class Person:
    name = 'John'
    age = 36

class Student(Person):
    id = 1

p1 = Person()
s1 = Student()

print(issubclass(Student, Person))
print(issubclass(Person, Student))

Output:

True
False

36. Python iter() Function

The iter() function returns an iterator object.

It takes two arguments, the first is the object, and the second is the sentinel.

mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

Output:

apple
banana
cherry

37. Python len() Function

The len() function returns the length of an object.

The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

mytuple = ("apple", "banana", "cherry")
print(len(mytuple))

mydict = {"name": "John", "age": 36}
print(len(mydict))

Output:

3
2

38. Python list() Function

The list() function returns a list (array).

The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

mytuple = ("apple", "banana", "cherry")
mylist = list(mytuple)
print(mylist)

mydict = {"name": "John", "age": 36}
mylist = list(mydict)
print(mylist)

Output:

['apple', 'banana', 'cherry']
['name', 'age']

39. Python locals() Function

The locals() function returns an updated dictionary of the current local symbol table.

It takes no arguments.

def myfunc():
    x = 300
    y = 200
    print(locals())

myfunc()

Output:

{'x': 300, 'y': 200}

40. Python map() Function

The map() function executes a specified function for each item in an iterable.

The item is sent to the function as a parameter.

def getLength(n):
    return len(n)

x = map(getLength, ('kiwi', 'melon', 'banana'))

# convert the map into a list, for readability:
print(list(x))

Output:

[4, 5, 6]

41. Python max() Function

The max() function returns the largest item in an iterable or the largest of two or more arguments.

mylist = [10, 20, 30, 40, 50]
print(max(mylist))

print(max(24, 12, 36))

Output:

50
36

42. Python memoryview() Function

The memoryview() function returns a memory view object from the given argument.

Memory view is a built-in type that provides C-stylebuffers for efficient access to the internal data of an object.

x = memoryview(bytes(5))

print(x)

Output:

<memory at 0x7fd7527f4b90>

43. Python min() Function

The min() function returns the smallest item in an iterable or the smallest of two or more arguments.

mylist = [10, 20, 30, 40, 50]
print(min(mylist))

print(min(24, 12, 36))

Output:

10
12

44. Python next() Function

The next() function returns the next item in an iterable.

It takes one argument, the iterator object.

mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

Output:

apple
banana
cherry

45. Python object() Function

The object() function returns a featureless object.

This is used when a new instance of an object is needed, but no arguments are required.

It is the most base type in Python.


46. Python oct() Function

The oct() function converts an integer number to an octal string prefixed with "0o".

print(oct(10))
print(oct(8))
print(oct(256))
print(oct(-95))

Output:

0o12
0o10
0o400
-0o137

47. Python open() Function

The open() function opens a file and returns it as a file object.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

In addition, you can specify if the file should be handled in binary or text mode:

# Open a file for reading
f = open("demofile.txt", "r")

# Open a file for writing
f = open("demofile2.txt", "w")

# Open a file for appending
f = open("demofile.txt", "a")

# Open a file for writing, and create it if it does not exist
f = open("demofile3.txt", "x")

48. Python ord() Function

The ord() function returns the number representing the Unicode code of a specified character.

This is the inverse of the chr() function.

print(ord("a"))
print(ord("A"))
print(ord("1"))
print(ord("€"))

Output:

97
65
49
8364

49. Python pow() Function

The pow() function returns the value of x to the power of y.

print(pow(4, 3))
print(pow(5, 2))
print(pow(2, 5))

Output:

64
25
32

50. Python print() Function

The print() function is the most often used function in Python. It is used to print the specified message to the screen, or another standard output device.

The message can be a string or any other object, the object will be converted into a string before being written to the screen.

print("Hello, World!")

By default, the print() function ends with a new line.

To avoid the newline, you can add a parameter at the end:

print("Hello, World!", end = "")

51. Python property() Function

The property() function returns a property attribute.

A property attribute has three methods, fget(), fset(), and fdel(), for getting, setting, and deleting a property value.

It is a built-in function of Python.

class Person:
    def __init__(self, name):
        self._name = name

    # Getter function
    def getName(self):
        return self._name

    # Setter function
    def setName(self, value):
        self._name = value

    # Delete function
    def delName(self):
        del self._name

    name = property(getName, setName, delName)

p1 = Person("John")
print(p1.name)

p1.name = "Mike"
print(p1.name)

del p1.name
print(p1.name)

Output:

John
Mike
AttributeError: 'Person' object has no attribute '_name'

52. Python range() Function

The range() function returns a sequence of numbers, starting from 0 by default, increments by 1 (by default), and ends at a specified number.

When the range() function is used with one parameter, the value is used as the end value.

for x in range(6):
    print(x, end = " ")

Output:

0 1 2 3 4 5

53. Python repr() Function

The repr() function returns a printable representation of the given object.

The repr() function is used to compute the "official" string representation of an object.

The repr() function is similar to str() function, but the str() function is used to compute the "informal" string representation of an object.

def my_function():
    pass

print(repr(my_function))

Output:

<function my_function at 0x7f124d9d6950>

54. Python reversed() Function

The reversed() is used to reverse the order of the elements in the iterable.

my_list = [1, 2, 3, 4, 5]
print(list(reversed(my_list)))

Output:

[5, 4, 3, 2, 1]

55. Python round() Function

The round() function returns the floating point number rounded to the given number of decimals.

If the number of decimals is not provided, it rounds the number to the nearest integer.

print(round(3.1415926))
print(round(3.1415926, 2))

Output:

3
3.14

56. Python set() Function

The set() function creates a set object and returns it.

A set is an unordered collection of items. Every element is unique (no duplicates) and must be immutable (cannot be changed).

However, the set itself is mutable. We can add or remove items from it.

my_set = set("Books")
print(my_set)

Output:

{'B', 'o', 'k', 's'}

57. Python setattr() Function

The setattr() function sets the value of the specified attribute of the specified object.

If the attribute does not exist, then it will be created.

class Person:
    name = "John"
    age = 36

p1 = Person()
print(f"Before - Name: {p1.name}")
print(f"Before - Age: {p1.age}")

# Set the age of the person to 40
setattr(p1, "age", 40)
print(f"After - Age: {p1.age}")

# Create a new attribute
setattr(p1, "salary", 60000)
print(f"Salary: {p1.salary}")

Output:

Before - Name: John
Before - Age: 36
After - Age: 40
Salary: 60000

58. Python slice() Function

The slice() function is used to create a slice object representing the set of indices specified by range(start, stop, step).

This slice object slices any sequence (such as string, tuple, and list). It starts from the start index and stops before the stop index and includes only the elements that are evenly divisible by the step.

my_string = "Python is fun!"
print(slice(1, 5, 2))
print(my_string[slice(1, 14, 2)])

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list1[slice(1, 5, 2)])

Output:

slice(1, 5, 2)
yhni u!
[2, 4]

59. Python sorted() Function

The sorted() function returns a sorted list from the elements of the given iterable.

The sorted() function does not change the original list.

If you do not specify any parameters, the default sort order is ascending, lowest to highest.

It accepts two parameters:

my_list = [5, 2, 3, 1, 4]
print(sorted(my_list))

my_list = [5, 2, 3, 1, 4]
print(sorted(my_list, reverse=True))

Output:

[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

60. Python staticmethod() Function

The staticmethod() function returns a static method for a function.

A static method does not require a class instance creation. So, it is not necessary to create a class instance before calling the static method.

To declare a static method, use the @staticmethod decorator.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @staticmethod
    def greet():
        print("This is a static method.")

# Call the static method
Person.greet()

Output:

This is a static method.

61. Python str() Function

The str() converts the specified value into a string.

It can be used to convert other data types like integers, floats, booleans, objects, etc into strings.

# integer to string
print(str(10))
# float to string
print(str(3.14))
# boolean to string
print(str(True))
# dictionary to string
print(str({"name": "John", "age": 36}))

Output:

10
3.14
True
{'name': 'John', 'age': 36}

62. Python sum() Function

The sum() function adds the items of an iterable and returns the sum.

You can pass the start parameter to it as a second argument. If start is not provided, 0 is taken as the default start value.

my_list = [1, 2, 3, 4, 5]
print(sum(my_list))

my_list = [1, 2, 3, 4, 5]
print(sum(my_list, 10))

Output:

15
25

63. Python super() Function

The super() function returns an object that represents the parent class.

By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.

For example, if you have a class named Person and you want to create a class named Student, which inherits the properties and methods from Person, you can use the super() function to inherit all the methods and properties from its parent.

class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(f"{self.firstname} {self.lastname}")
        
class Student(Person):
    def __init__(self, fname, lname):
        super().__init__(fname, lname)

x = Student("John", "Doe")
x.printname()

Output:

John Doe

64. Python tuple() Function

The tuple() function converts an iterable (list, string, set, dictionary) to a tuple.

my_list = [1, 2, 3, 4, 5]
print(tuple(my_list))

my_string = "Hello World"
print(tuple(my_string))

my_set = {1, 2, 3, 4, 5}
print(tuple(my_set))

Output:

(1, 2, 3, 4, 5)
('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd')
(1, 2, 3, 4, 5)

65. Python type() Function

The type() function returns the type of the specified object.

You can pass any object (string, number, list, dictionary, etc.) to the type() function, and it will return the type of the object.

print(type("Hello World"))
print(type(20))
print(type(20.5))
print(type(["apple", "banana", "cherry"]))
print(type(("apple", "banana", "cherry")))

Output:

<class 'str'>
<class 'int'>
<class 'float'>
<class 'list'>
<class 'tuple'>

66. Python vars() Function

The vars() function returns the __dict__ property of the specified object.

The __dict__ property contains the object's properties.

class Person:
      name = "John"
      age = 36

print(vars(Person))

Output:

{'__module__': '__main__', 'name': 'John', 'age': 36, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}

67. Python zip() Function

The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and return them.

If you do not pass any parameter, zip() returns an empty iterator.

my_list = [1, 2, 3]
your_list = [10, 20, 30]

zip_obj = zip(my_list, your_list)
print(list(zip_obj))

Output:

[(1, 10), (2, 20), (3, 30)]

References

Reference: Python library