Python zip() Function

The Python zip() function aggregates elements from two or more iterables and zip them into a single iterable. The result of the zip() function is an iterator of tuples that contains elements from each iterable you have passed into the zip(). This iterator can later be converted to any desired type of iterable like a list, dictionary, etc based on the requirement.

first_name = ['John', 'James', 'Jennifer']
last_name  = ['Doe', 'Bond', 'Smith']

students = zip(first_name, last_name)

print(list(students))

# Output:
# [('John', 'Doe'), ('James', 'Bond'), ('Jennifer', 'Smith')]

Syntax of the zip() Function

The syntax of the zip() function is as follows:

zip(*iterables)

zip() Function Parameters

The zip() function takes in iterables as arguments such as lists, sets, tuples, dictionaries, etc. It can take any number of iterables at a time.


zip() Function Return Value

The zip() function returns a zip object. This zip object is basically an iterator containing items from all the iterables passed to the zip() function. This zip object can later be converted to any type of iterable such as list, dictionary, set, etc.


Understanding the zip() Function

At the beginning of this tutorial, we learned that the Python zip() function aggregates elements from two or more iterables and results into a single iterator. Now, let’s understand it with the help of a real-world example.

Suppose, you have two lists containing the first names and last names of university students. Your task is to combine the first names with the corresponding last names. How would you do that? Well, the answer is the Python zip() function.

The Python zip() function aggregates elements that are on the same index in different iterables and returns an iterator containing all such combinations. See the example below:

Example 1: Combining first name and last name

first_name = ['John', 'James', 'Jennifer']
last_name  = ['Doe', 'Bond', 'Smith']

students = zip(first_name, last_name)

print(list(students))

Output:

[('John', 'Doe'), ('James', 'Bond'), ('Jennifer', 'Smith')]

Example 2: Combining first name, last name and age

In the previous example, we zipped the first names with their corresponding last names using the zip().

Now, let’s add one more field, the age of the students with their corresponding first and last names. To do that we have to pass one more parameter i.e. age to the zip() function and our task will be done.

first_name = ['John', 'James', 'Jennifer']
last_name  = ['Doe', 'Bond', 'Smith']
age = [18, 19, 20]

students = zip(first_name, last_name, age)

print(list(students))

Output:

[('John', 'Doe', 18), ('James', 'Bond', 19), ('Jennifer', 'Smith', 20)]

Passing One Argument

The zip() function can also take just one argument. In this case, the zip() function returns an iterator that contains a list of 1-item tuples.

Example:

nums = [1, 2, 3, 4]

a = zip(nums)

print(list(a))

Output:

[(1,), (2,), (3,), (4,)]

Passing No Arguments

You can also call the zip() function without passing any arguments to it. In this case, the zip() function returns an empty iterator.

Example:

a = zip()
print(list(a))

Output:

[ ]

Passing Arguments of Unequal Length

There might be situations where the length of the iterables that we are passing as the arguments is unequal. In such cases, the zip() function returns an iterator which has the same length as the shortest iterable. The remaining items in the longer iterables are completely ignored by the zip() function.

Example:

numbers = [1, 2, 3]
letters = ['a', 'b', 'c', 'd', 'e', 'f']

zipped = zip(numbers, letters)

print(list(zipped))

Output:

[(1, 'a'), (2, 'b'), (3, 'c')]

In the above example, the length of the shortest iterable is 3. Therefore only the first three items from both the iterables are considered. The remaining items(‘d’, ‘e’ & ‘f’) have no match therefore they are completely ignored.


Creating Dictionaries using zip()

Sometimes, you might have a requirement where you need to build a dictionary from two similar types of sequences. This can be easily achieved using the zip() function.

In the below example, we have two lists containing information of a student. We have zipped these two lists and created a single dictionary from them.

Example:

keys = ['first_name', 'last_name', 'age', 'gender']
values = ['John', 'Doe', 23, 'Male']

student = zip(keys, values)

print(dict(student))

Output:

{'first_name': 'John', 'last_name': 'Doe', 'age': 23, 'gender': 'Male'}

Using for loop with zip()

In Python, you might have come across a situation where you have to iterate over multiple iterables at the same time. For example, iterating through multiple lists, tuples, sets, or any other sequence. This can be very easily achieved using the zip() function.

As the zip() function returns a series of tuples. Therefore, we can easily unpack these tuple items in the declaration of the for loop.

Example 1: Traversing lists in parallel

keys = ['first_name', 'last_name', 'age', 'gender']
values = ['John', 'Doe', 23, 'Male']

for key, value in zip(keys, values):
    print(key,': ',value)

Output:

first_name :  John
last_name :  Doe
age :  23
gender :  Male

Example 2: Traversing dictionaries in parallel

Similar to the lists, we can traverse multiple dictionaries in parallel as well. But to access key-value pairs from all dictionaries, we have to make use of the items() function. See implementation in the below example:

stud1 = {'first_name': 'John', 'last_name': 'Doe', 'age': 23}
stud2 = {'first_name': 'Jennifer', 'last_name': 'Smith', 'age': 24}

for (k1, v1), (k2, v2) in zip(stud1.items(), stud2.items()):
    print(k1,': ', v1)
    print(k2,': ', v2)

Output:

first_name :  John
first_name :  Jennifer
last_name :  Doe
last_name :  Smith
age :  23
age :  24

Unzipping Values

Till now, we have understood a lot about zipping the sequences. But now the question that comes in mind is ‘How can we unzip a sequence?’ Is there any inbuilt method that does just the reverse of the zip()? Well, there is no such inbuilt method in Python.

The answer to this question is the zip() function itself. The zip() function can perform both zipping and unzipping of sequences. To unzip a sequence we have to use the zip() function with the unpacking operator *. See the example given below:

Example:

student = [('first_name', 'John'), ('last_name', 'Doe'), ('age', 23)]

keys, values = zip(*student)

print('keys =', keys)
print('values =', values)

Output:

keys = ('first_name', 'last_name', 'age')
values = ('John', 'Doe', 23)

Python filter() Function

The filter() function in Python is used to extract those items from an existing iterable that satisfy a given condition. For example, filtering all even numbers from a list of numbers, or filtering all positive numbers from the list of numbers, or any such kind of operation. This process is known as a filtering operation.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def is_even(num):
    if num % 2 == 0:
        return True
        
even_numbers = filter(is_even, numbers)

print(list(even_numbers))

# Output
# [2, 4, 6, 8, 10]

Syntax of filter()

The syntax of the filter() function is as follows:

filter(function, iterable)

Parameters of filter()

The filter() function takes in two arguments:

  • function – A filtering function that removes unwanted items from the sequence by putting some condition. It must be a single parameter function.
  • iterable – A sequence of items on which the filtering opeation has to be preformed.

filter() Return Value

The filter() function returns an iterator. This iterator contains only those items which satisfy the condition written inside the filtering function.

This iterator can later easily be converted to other iterable sequences like lists, sets, tuples, etc. based on your requirement.


Understanding Python filter() Function

Now that we have understood the basic syntax of the filter() function. Let’s move on to its actual working with the help of some basic examples.

Suppose, we have a list of some positive numbers and we want to filter out only the even numbers from it without modifying the actual list. How would you do that? Well, the most common approach to do this is using a for loop. See the example below:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []

for num in numbers:
    if num % 2 == 0:
        even_numbers.append(num)

print(even_numbers)

Output:

[2, 4, 6, 8, 10]

You can see from the above output that we got the desired result. But is it the only way to achieve this? Well, no. We can also achieve the same result using the filter() function in a much easier way. So, let’s understand it in detail.

The filter() function takes exactly two parameters. The first is the filtering function that helps us removing unwanted items from the list and considering only the desired ones. The second is a sequence of items on which the filtering operation is performed.

Just like the for loop, the filter() function also iterates over each element of the given sequence and implicitly passes each item to the filtering function as its argument.

Now the filtering function checks whether the current item satisfies the given condition or not. If the current item matches the given condition, the filtering function returns a boolean value True. This sends a signal to the filter() function that the current item should be considered as a part of the final output.

Otherwise, if the current item does not satisfy the given condition, it is excluded from the final result. See the implementation in the example below:

Example: Filter all even numbers from the list

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def is_even(num):
    if num % 2 == 0:
        return True
        
even_numbers = filter(is_even, numbers)

print(list(even_numbers))

Output:

[2, 4, 6, 8, 10]

Python filter() with dictionary

Similar to the lists, we can also apply the filter() function to filter out desired data from Python dictionaries. Here, the only thing we have to keep in mind is that the filter() function passes only keys to the filtering function as an argument, not the key-value pair.

In the example below, we have a dictionary that contains the student’s name as a key, and the marks as its value. The task is to filter out all the students that have marks more than 75.

students = {
    'John': 87.5,
    'Alice': 62,
    'Bob': 67.5,
    'Carl': 75.9,
    'Ann': 82,
    'Liz': 78.4
}

def is_applicable(key):
    if students[key] > 75:
        return True
        
applicable_students = filter(is_applicable, students)

print(list(applicable_students))

Output:

['John', 'Carl', 'Ann', 'Liz']

Python filter() with lambda Function

Similar to the map() function, we can also use the lambda function with the filter() function. The working of the lambda function is similar to a regular function except that it does not have a return statement because its body is automatically returned.

The main advantage of the lambda function is that we have to write less code.

Example 1: Filter even numbers from the list using lambda function

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers = filter(lambda num: num%2 == 0, numbers)

print(list(even_numbers))

Output:

[2, 4, 6, 8, 10]

Example 2: Filter students having marks more that 75% using lambda function

students = {
    'John': 87.5,
    'Alice': 62,
    'Bob': 67.5,
    'Carl': 75.9,
    'Ann': 82,
    'Liz': 78.4
}

applicable_students = filter(lambda key: students[key] > 75, students)

print(list(applicable_students))

Output:

['John', 'Carl', 'Ann', 'Liz']

Using None as a Function with filter()

The first parameter of the filter() function can also be None. In this case, the filter function removes all the values from the sequence that evaluate to False.

data = [1, False, True, None, 0, '', '0', '1']

truthy_values = filter(None, data)

print(list(truthy_values))

Output:

[1, True, '0', '1']

Python id() Function

The id() function in Python returns the identity of an object. This integer id actually represents the address of the object where it is stored in the memory. This id remains constant during the lifetime of the object. This means if you rerun the program the id value is not guaranteed to be the same.

name = 'John'

print('id of name is: ', id(name))

# Output
# id of name is:  139697701582896

Syntax of id()

The syntax of the id() function is as follows:

id(object)

Parameters of id()

The id() function accepts only one parameter:

  • object – The object whose identity has to be returned

id() Return Values

The id() function returns an integer value which represents the address of the object in the memory.


Python id() for Literal Values

A literal is raw data assigned to a variable or constant in our program. All literals in Python are objects. This means they definitely have a unique identity. Let’s see if they do have an Id associated.

Example :

# Id of integers
print(id(10))

# Id of float numbers
print(id(10.23))

# Id of string values
print(id('Hello'))

Output:

9788896
139769290373392
139769289934960

Note: The value of Id can differ on your computer.


Python id() for Variables

Similar to literals, variables are also objects in Python. These variables also have a unique Id. The length of the Id depends on the type of data stored in the variable.

Example 1: When the values stored in the variables are different

If values(data) stored in variables are not the same, the Id of each variable will be unique. See the example below:

a = 10
print('Id of a: ', id(a))

b = 20
print('Id of b: ', id(b))

Output:

Id of a:  9788896
Id of b:  9789216

Example 2: When the values stored in variables are exactly the same

If two or more variables in Python contain exactly the same value(data), it is guaranteed that their Id would be exactly the same. Python does this to minimize the memory space used by our program. This is known as caching in Python.

a = 10
print('Id of a: ', id(a))

b = 10
print('Id of b: ', id(b))

Output:

Id of a:  9788896
Id of b:  9788896

You can try out with other values also. The variables having the same values will have the same Id value.


Python id() for Immutable Objects

In the previous example, we saw that the id() function returns the same Id if two variables contain the same value. But, now the question arises will it work for other data types also?

Well, In simple words, Python caching is performed only for immutable objects. This means if two or more immutable objects(like strings, tuples, floats, numbers) have the same values(data), It is guaranteed that their Id would definitely be the same.

Example:

# Id of strings
str1 = 'abc'
str2 = 'abc'

print('Id of str1: ', id(str1))
print('Id of str2: ', id(str2))
print(id(str1)==id(str2))

# Id of tuples
tuple1 = ('a', 'b', 'c', 'd')
tuple2 = ('a', 'b', 'c', 'd')

print('\nId of tuple1: ', id(tuple1))
print('Id of tuple2: ', id(tuple2))
print(id(tuple1)==id(tuple2))

Output:

Id of str1:  139738371420848
Id of str2:  139738371420848
True

Id of tuple1:  139738371156304
Id of tuple2:  139738371156304
True

You can easily observe from the above output that the strings and tuples having the same data have the same Id value.


Python id() for Mutable Objects

In the last example, we saw that if two or more immutable objects contain the same data, their Id will be exactly the same. Does the same rule apply to mutable objects also? Well, the answer is no.

Mutable objects(lists, sets, dictionaries, etc) always have a unique Id irrespective of the data they contain. This means even if two mutable objects have exactly the same data, their Id would never be the same.

Example:

a = [1, 2, 3, 4]
b = [1, 2, 3, 4]

print('Id of a: ', id(a))
print('Id of b: ', id(b))

print(id(a) == id(b))

Output:

Id of a:  140021326610112
Id of b:  140021325973952
False

Python id() for Custom Objects

Similar to mutable objects, the Id of custom(user-defined) objects is always unique even if they contain exactly the same data.

Example:

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age  = age
        
student1 = Student('John', 23)
student2 = Student('John', 23)

print('Id of student1: ', id(student1))
print('Id of student2: ', id(student2))

print(id(student1) == id(student2))

Output:

Id of student1:  140324975477952
Id of student2:  140324974844080
False

Python getattr() Function

Python getattr() function is used to get the value of an object’s attribute. If the given attribute does not exist on the object, this function returns a default value.

class Student:
    name = 'John'
    age  = 24
 
student = Student()
 
print('Student name: ', getattr(student, 'name'))
print('Student age: ', getattr(student, 'age'))
 
# Output
# Student name:  John
# Student age:  24

getattr() Syntax

The syntax of the getattr() function is as follows:

getattr(object, attribute, defaultValue)

getattr() Parameters

The getattr() function accepts below three parameters:

  • object – The object whose attribute’s value to be fetched
  • attribute – The name of the attribute whose value has to be fetched. It has to be a string.
  • defaultValue – A value that is to be returned if given attribute does not exist.

getattr() Return Value

The getattr() function returns:

  • Actual value of the attribute for the given object if it exists
  • A default value if the given attribute does not exist on the object
  • AttributeError, if the givent attribute does not exist and no default value is supplied

getattr() Examples

In the example below, we have created a class Student which has an object named student. Let’s try to fetch the values of student’s name and age attributes using getattr() function.

Example 1: When the named attribute exists

class Student:
    name = 'John'
    age  = 24
 
student = Student()
 
print('Student name: ', getattr(student, 'name'))
print('Student age: ', getattr(student, 'age'))

Output:

Student name:  John
Student age:  24

Example 2: When the named attribute does not exist

In the above example, we have fetched the values of the name and age attributes and it worked as expected. Now, let’s try to fetch the value of an attribute that does not exist on the student object.

class Student:
    name = 'John'
    age  = 24
 
student = Student()
 
print('Student gender: ', getattr(student, 'gender'))

Output:

Traceback (most recent call last):
  File "<string>", line 7, in <module>
AttributeError: 'Student' object has no attribute 'gender'

It didn’t work right. Now the question is, can we anyhow avoid getting this error? Well, the answer to this is in the next example.


Example 3: Passing the default parameter to the gettattr() function

In the last example, we saw that when we tried to access the value of an attribute that does not exist on the object, we got an error. Actually, this is the main advantage of the getattr() function over the traditional dot(.) operator that we can pass a default value to the getattr() function.

If the attribute does not exist, the getattr() function returns the default value and if it does, it will return its original value. See the example below:

class Student:
    name = 'John'
    age  = 24
 
student = Student()

# Pass a default value Male 
print('Student gender: ', getattr(student, 'gender', 'Male'))

Output:

Student gender:  Male

As you can see from the above output, the attribute named ‘gender’ does not exist on the student object still it returned a value ‘Male’. This is because we passed the third parameter to the getattr() function which is returned as a default value in case the given attribute does not exist.


Python setattr() Function

Python setattr() function is used to set the value of an attribute for a given object. This function gives you an alternative to assign the attribute value without using the dot(.) operator.

If the attribute already exists, the setattr() function updates its existing value, otherwise, it creates a new attribute under that object and assigns the given value to it.

class Student:
    name = 'John'

student = Student()

# Set 'age' attribute to 23
setattr(student, 'age', 23)    

print('Student name: ', student.name)
print('Student age: ', student.age)

# Output
# Student name:  John
# Student age:  23

setattr() Syntax

The syntax of the setattr() function is as follows:

setattr(object, attribute, value)

setattr() Parameters

The setattr() function takes in three parameters:

  • object – The target object whose attribute has to be set
  • attribute – Name of the attribute to be set
  • value – The value of the attribute

setattr() Return Value

The setattr() function returns the None object.


Python setattr() Examples

In the example below, we have created a class named Student. This Student class has only one attribute ‘name’. Therefore, by default, all of its objects will have only and only one attribute i.e ‘name’.

Now suppose you want to add some additional information to any individual student. You can simply achieve this using the setattr() function.

In the example below, we have added an extra attribute ‘age’ to the student object using the setattr() function.

Example 1: Set object attributes using setattr()

class Student:
    name = 'John'

student = Student()

# Set 'age' attribute to 23
setattr(student, 'age', 23)    

print('Student name: ', student.name)
print('Student age: ', student.age)

Output:

Student name:  John
Student age:  23

Example 2: Set class attributes using setattr()

The setattr() function is not just restricted to objects. It can also be used to set class attributes. This is very helpful in situations where we need to add the same attribute to each object of the class.

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

student1 = Student('John', 23)
student2 = Student('James', 24)

# Set 'section' attribute to 'D' for class Student
setattr(Student, 'section', 'D')    

print('Student1 name: ', student1.name)
print('Student1 age: ', student1.age)
print('Student1 section: ', student1.section)

print('\nStudent2 name: ', student2.name)
print('Student2 age: ', student2.age)
print('Student2 section: ', student2.section)

Output:

Student1 name:  John
Student1 age:  23
Student1 section:  D

Student2 name:  James
Student2 age:  24
Student2 section:  D

Python setattr() vs Regular Assignment

At the beginning of this tutorial, we learned that the setattr() function is an alternative to the regular assignment using the dot(.) operator. I mean to say is that we can set or modify a class or object attribute using the dot(.) operator. If it is so then why do we use the setattr() function?

Well, using regular assignments we can set only static attributes, but not user-defined.

In the example below, we are trying to set a new user-defined attribute to the student object. Let’s see if it works.

Example 1: The problem with regular assignment

class Student:
    name = 'John'
 
student = Student()

attrName  = input('Enter attribute name: ')
attrValue = input('Enter attribute value: ') 

student.attrName = attrValue

print('Student name: ', student.name)
print('Student age: ', student.age)

Output:

Enter attribute name: age
Enter attribute value: 24
Student name:  John
Traceback (most recent call last):
  File "<string>", line 13, in <module>
AttributeError: 'Student' object has no attribute 'age'

Damn! It didn’t work. But why? This is because the assignment student.attrName = attrValue sets a new attribute named ‘attrName’ on the student object not ‘age’ that we were expecting. Now because the ‘age’ attribute does not exist therefore we got the AttributeError.


Example 2: Solution to the above problem

A simple solution to the above problem is using the setattr() function instead of the regular assignment using the dot(.) operator. Just look at the example below:

class Student:
    name = 'John'
 
student = Student()

attrName  = input('Enter attribute name: ')
attrValue = input('Enter attribute value: ') 

setattr(student, attrName, attrValue)

print('Student name: ', student.name)
print('Student age: ', student.age)

Output:

Enter attribute name: age
Enter attribute value: 24
Student name:  John
Student age:  24

It works!!! I hope now you got the idea what are the benefits of using setattr() over the regular assignment.


Recommended Articles

Python map() Function

Sometimes you might face situations where you need to perform the same operation on each and every element of an iterable(list, tuple, set, etc). For example, square each number or add 10 to each number, or any such kind of operation.

The most common approach to achieve this is using a for or while loop and perform the same operation on each element. But, there is a much easier solution to this problem. Yes, the map() function.

The map() function is used in situations where we need to perform the same operation on each element of an iterable, without using any explicit for or while loop.

numbers = [1, 2, 3, 4, 5]
 
def square(num):
    return num*num
 
squares = list(map(square, numbers))
print(squares)

# Output
# [1, 4, 9, 16, 25]

map() Function Syntax

The syntax of the map() function is as follows:

map(function, iterable, ...)

map() Function Parameters

The map() function takes two parameters:

  • function – A function that performs same operation on each element of the iterable
  • iterable – The iterable on which the operation is to be performed. There can be one or more such iterables.

map() Function Return Value

The map() function returns an object of the map class. This map object contains the updated value of each item of the iterable on which we have performed the operation.

The map object can be later converted to any desired sequence like a list, tuple, set, etc.


Understanding the map() Function

Now that we have learned the basic syntax and some theoretical parts of the map() function. Let’s now understand how it actually works.

Like the for loop, the map() function iterates over each element of the iterable and one by one passes each element to the function that we have given as the first parameter.

This function then performs some operations on the current element which is passed to it and returns its new(modified) value.

Python map() Function

Example:

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

def square(num):
    return num*num

result = map(square, numbers)
print(result)

# Convert map object to list
resultList = list(result)
print(resultList)

Output:

<map object at 0x7fe4a17d71f0>
[1, 4, 9, 16, 25]

In the above example, the map(square, numbers) function passes each element of the numbers list to the square(num) function one by one as an argument num. The square function then calculates the square of the current num and returns it to the map() function again.

The map object is later converted to a list using the inbuilt list() function. You can also convert the map object to other sequences like: tuples, sets, etc.


map() Function with Multiple Iterables

It is also possible to pass multiple iterables to the map() function at a time. The basic functionality remains the same. The only difference is that the map() function now implicitly passes multiple elements(one from each iterable) to the function defined in the first parameter.

In the example below, the map() function adds the corresponding items of the numbers1 and numbers2 list and returns a new map object containing the corresponding items’ sum from both lists.

Example 1: When all iterables are of the same size

numbers1 = [1, 2, 3, 4, 5]
numbers2 = [10, 20, 30, 40, 50]

def add(num1, num2):
    return num1 + num2

result = map(add, numbers1, numbers2)
print(result)

# Convert map object to list
resultList = list(result)
print(resultList)

Output:

<map object at 0x7fd93bd57430>
[11, 22, 33, 44, 55]

Example 2: When all iterables are of different sizes

If all the iterables are of different sizes, the map() function iterates until the iterable with the minimum number of items has some items to be iterated. Once all these items are iterated, the map() function ignores the remaining items in other iterables.

numbers1 = [1, 2, 3]
numbers2 = [10, 20, 30, 40, 50]

def add(num1, num2):
    return num1 + num2

result = map(add, numbers1, numbers2)
print(result)

# Convert map object to list
resultList = list(result)
print(resultList)

Output:

<map object at 0x7f2b9df06250>
[11, 22, 33]

Python map() with lambda Function

Just like the normal function, a lambda function can also be used with the map function. The basic functionality remains exactly the same. The only difference is that we have to write less code.

Example:

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

result = map(lambda num: num*num, numbers)
print(result)

# Convert map object to list
resultList = list(result)
print(resultList)

Output:

<map object at 0x7f407e935130>
[1, 4, 9, 16, 25]

Python map() and lambda with Multiple Parameters

In previous examples, we used a custom add() function with the map() function to add corresponding items in multiple iterables passed to the map(). Now the question arises can we replace the custom add() function with a lambda expression to do the same task? The answer is yes.

Just like a normal function, the basic functionality of the lambda expression remains the same i.e. the map() function passes one item from each of the iterables to the lambda expression at a time and then moves to the next item and so on.

Example:

numbers1 = [1, 2, 3, 4, 5]
numbers2 = [10, 20, 30, 40, 50]

result = map(lambda num1,num2: num1+num2, numbers1, numbers2)
print(result)

# Convert map object to list
resultList = list(result)
print(resultList)

Output:

<map object at 0x7f3907599250>
[11, 22, 33, 44, 55]

Python map() with inbuilt Functions

Similar to a lambda function, an inbuilt Python function can also be used with the map() function. Just like the lambda function, the iterables are implicitly passed to this inbuilt function as its parameters by the map() function.

In the below example, we have used Python inbuilt pow() function with the map() function to calculate the power of each element in the numbers list. The corresponding power values are stored in the powers list.

The number and its corresponding power is implicitly passed to the pow(num, pow) function by the map().

Example:

numbers = [1, 2, 3, 4, 5]
powers  = [2, 2, 3, 2, 3]
 
result = map(pow, numbers, powers)
print(result)
 
# Convert map object to list
resultList = list(result)
print(resultList)

Ouput:

<map object at 0x7fad9080b220>
[1, 4, 27, 16, 125]

Python hasattr() Function

Python hasattr() function is used to check the presence of an attribute in a given object. It returns a Boolean value, either True or False based on the presence of the attribute in that object. If the attribute is present it returns True otherwise False.


Syntax of hasattr() Funtion

The syntax of the hasattr() function is as follows:

hasattr(object, name)

hasattr() Parameters

The hasattr() function accepts two parameters:

  • object – It can be any object wherein we want to check the presence of the attribute
  • name – The name of the attribute whose presence is to be checked in the object. This value has to be a string.

hasattr() Return Value

The hasattr() function always returns a Boolean value based on the presence of the attribute in the given object. It returns:

  • True – If the attribute is present in the object
  • False – If the attribute does not exist in the object

Working of hasattr() Function

The theoretical part we have understood. Now, let’s understand how it actually works with the help of an example.

To understand the working of the hasattr() function, we have to first create a class and some objects of it and then we will check if the given attribute exists. Refer to the example below:

Example:

class Student:
    name = 'John'
    age  = 23

student = Student()

print('Does student has name?: ', hasattr(student, 'name'))
print('Does student has marks?: ', hasattr(student, 'marks'))

Output:

Does student has name?:  True
Does student has marks?:  False

In the above example, the student object has the ‘name’ attribute. Therefore, hasattr(student, 'name') returns True. While the ‘marks’ attribute does not exist, hence returns False.


Check if a named method exists using hasattr()

In the previous example, we learned how to check if a named attribute exists on an object. But now the question arises, can we check if a named method exists on an object using hasattr()? The answer is yes.

The second parameter can be the name of any variable or method. The only constraint is that it should be a string. Refer to the example below.

Example:

class Student:
    name = 'John'
    age = 23
    
    def printAge(self):
        print(self.name, ' age is ', self.age)

student = Student()

student.printAge()
print('Does student has printAge()?: ', hasattr(student, 'printAge'))
print('Does student has printName()?: ', hasattr(student, 'printName'))

Output:

John  age is  23
Does student has printAge()?:  True
Does student has printName()?:  False

Python input() Function

The input() function in python is used to take input from a user. It prompts a message to the user before taking the input value and after the user enters input, it returns the input as a string.

age = input('Enter your age: ')
print(age)

# Output
# Enter your age: 24
# 24

input() Function Syntax

The syntax of the input() function is given below:

input(message)

input() Function Parameters

The input() function takes only a single optional parameter:

  • message – (Optional) The message is prompted to the user before taking the input value.

input() Function Return Value

The input() function returns the input value entered by the user as a string.

This is to be noted that the input() function returns only and only a string value. This means, even if the user has entered an integer value it will convert it to a string.

input() Function Examples

Let’s try to understand the working of the input() function with the help of relevant examples.

Example 1: Take input from user and print it

In the example below, no message is prompted to the user before taking the input value.

Python input() function without prompt
# Take input with any messagae
name = input()

print('Your name is:', name)

Output:

John
Your name is: John

Example 2: Take input from user with a prompt

Asking an input from the user without prompting any message is a little bit confusing for the user. Therefore, in the example below, we have prompted a message ‘Enter your name’ to the user before taking the input.

Python input() Function with prompt
# Take input with a message
name = input('Enter your name: ')

print('Your name is:', name)

Output:

Enter your name: John
Your name is: John

Take integer input from user

As I already mentioned, the return type of the input() function is always a string. Then the question arises how can one take integer input from the user?

Well, it sounds tough but it isn’t. All you have to do is convert the user input from string to integer using the inbuilt int() function. See the example below:

Example:

age = input('Enter your age: ')
print('Type of age is: ', type(age))

age = int(input('Enter your age: '))
print('Type of age is: ', type(age))

Output:

Enter your age: 24
Type of age is:  <class 'str'>
Enter your age: 24
Type of age is:  <class 'int'>

Take Multiple inputs from User

A very common problem that Python developers generally face is how to take multiple inputs from a user at once. Well, there are several ways to accomplish it. But we are gonna learn only the most efficient and common methods that developers use.

1. Using multiple input() functions

The simplest way to take multiple inputs is to write the input() function multiple times. See the example below:

a, b = input('Enter a: '), input('Enter b: ')

print('a = ', a)
print('b = ', b)

Output:

Enter a: 10
Enter b: 20
a =  10
b =  20

2. Using split() function with input() function

This is the shortest way to take multiple inputs from a user. But here we can only show a single message to the user and he has to separate input values with a space. See the example below:

a, b = input('Enter Two Values: ').split()

print('a = ', a)
print('b = ', b)

Output:

Enter Two Values: 10 20
a =  10
b =  20

Take Multiple integer inputs from user

We have discussed how to take integer input from the user and also how to take multiple inputs from the user. Now, what if I want to take multiple integer inputs from a user in a single line. well, this is what we are gonna learn here.

As we discussed in the beginning of this tutorial that the input() function returns only and only string type. So how can we expect it to return integers? That’s right, it will return only string but at the time of taking the input, we will convert it to an integer. This is achieved by the map() function. See the example below:

a, b = map(int, input('Enter Two Values: ').split())

print('a = ', a, ' and type is: ', type(a))
print('b = ', b, ' and type is: ', type(b))

Output:

Enter Two Values: 10 20
a =  10  and type is:  <class 'int'>
b =  20  and type is:  <class 'int'>

Python range() Function

Python range() function is very popular and widely used especially when you are working with the for and while loops. This function returns an immutable sequence of numbers in a given range. Using this function you can even generate a sequence of numbers in a given step size.

In this tutorial, we are going to learn the working of the range() function with the help of relevant examples in detail.

numbers = range(5)
numbers = list(numbers)
print(numbers)

# Output: [0, 1, 2, 3, 4]

Syntax of range() Function

The syntax of the range() function is as follows:

range(start, stop, step)

range() Function Parameters

The range() function can accept one, two, or at most three parameters. These parameters are given below:

  • start – (Optional) An integer which is the starting point of the sequence. The default value is 0.
  • stop – An integer value denoting the ending point of the sequence. This is never included in the end result.
  • step – (Optional) An integer value denoting the incremental change between any two consecutive numbers in the sequence. The default value of step size is 1.

range() Function Return Value

The range() function returns an immutable sequence of numbers of type range. It returns an empty sequence if the start and stop both parameters value is the same. Don’t worry we will discuss each possible combination in detail.


Working of range() Function

The result of the range() function depends on the number of parameters passed to it. Therefore, we will first pass only one parameter(stop), then two(start & stop), and then three(start, stop & step) and will understand the working of the range() function in each case. So, let’s get started.

1. Pass only one parameter(stop) to the range() function

When we pass only one parameter to the range() function, it starts the sequence from 0 and ends at stop-1 value i.e. stop value is never the part of the sequence.

Python range() function

Example :

numbers = list(range(0))
print(numbers)

numbers = list(range(5))
print(numbers)

numbers = list(range(10))
print(numbers)

Output:

[]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

2. Pass two parameters(start & stop) to the range() Function

As we saw in the above example, by default the range() function starts at 0. But, if we want to start it at any other integer, we can easily do this by passing the start parameter to it.

Python range() function with start parameter

Example :

numbers = list(range(1, 10))
print(numbers)

numbers = list(range(5, 10))
print(numbers)

numbers = list(range(7, 10))
print(numbers)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9]
[7, 8, 9]

3. Pass all three parameters(start, stop & step) to the range() Function

What if we want a sequence of numbers starting from 1 to 10 with an incremental difference of 2 or 3? Well, the third parameter(step) of the range() function helps us achieving this. See the example given below:

Python range() function with step parameter

Example:

numbers = list(range(1, 10, 1))
print(numbers)

numbers = list(range(1, 10, 2))
print(numbers)

numbers = list(range(1, 10, 3))
print(numbers)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]
[1, 4, 7]

range() function with negative values

Sometimes a situation may occur where you need a sequence of negative numbers like excessing list items from the end of it. In such situations, the range() function becomes very helpful. Because we don’t have to explicitly make the number negative as the range() function takes care of that.

Python range() function with negative step

Example : Reverse range() function

numbers = list(range(-10))
print(numbers)

numbers = list(range(-10, -1))
print(numbers)

numbers = list(range(-10, -1, 2))
print(numbers)

Output:

[]
[-10, -9, -8, -7, -6, -5, -4, -3, -2]
[-10, -8, -6, -4, -2]

range() function with for loop

As I already mentioned, the range() function is mainly used with the for loop and it’s time to implement what I said. So let’s just do that.

Example 1: Print all even numbers from 1 to 10.

for i in range(2, 11, 2):
    print(i)

Output:

2
4
6
8
10

Example 2: Access list items using range()

numbers = [1, 2, 3, 4, 5]
length  = len(numbers)
for i in range(length):
    print(numbers[i])

Output:

1
2
3
4
5

Accessing range() Items

As we already discussed, the range() function returns a sequence object of numbers in a given range. Therefore, like the lists and tuples, its items can also be accessed using both positive and negative indexing.

Example 1: Access range() items using positive indexing

numbers = range(5)
print('numbers[0] is', numbers[0])
print('numbers[1] is', numbers[1])
print('numbers[2] is', numbers[2])

Output:

numbers[0] is 0
numbers[1] is 1
numbers[2] is 2

Example 2: Access range() items using negative indexing

numbers = range(5)
print('numbers[-1] is', numbers[-1])
print('numbers[-2] is', numbers[-2])
print('numbers[-3] is', numbers[-3])

Output:

numbers[-1] is 4
numbers[-2] is 3
numbers[-3] is 2

Python len() Function

The len() function in Python is an inbuilt function that returns the total number of items(length) in an iterable object. This function is very common in use as it can be used to get the length of any iterable object like a string, list, dictionary, etc.

In this tutorial, we are going to learn how the len() function works, and also we will understand how it can be used to find out the length of the list, string, tuples, and dictionaries with the help of examples.

fruits = ['Apple', 'Mango', 'Orange', 'Banana']

# Find the length of the fruits list
length = len(fruits)
print(length)

# Output: 4


Syntax of the len() Function

The syntax of the len() function is:

len(iterable_object)

The len() Function Parameters

The len() function takes in a single parameter which can be a sequence like a list, string, tuple, etc., or a collection(dictionary and set). This parameter is required.

Passing a non-iterable object as a parameter will raise a TypeError exception.


The len() Funtion Return Value

The len() function returns an integer value denoting the total number of items in the given iterable object. If the iterable is empty, it returns 0.


Using Python len() Function to find the length of a List and Tuple

In the example below, we have used the len() function to find the length of a list and tuple. It counts the total number of items in them and returns as an integer value.

Example 1:

fruits = []   # Empty List
print('Length of', fruits, 'is', len(fruits))

fruits = ['apple', 'mango', 'orange', 'banana']
print('Length of', fruits, 'is', len(fruits))

numbers = ()  # Empty Tuple
print('Length of', numbers, 'is', len(numbers))

numbers = (1, 2, 3, 4, 5)
print('Length of', numbers, 'is', len(numbers))

Output:

Length of [] is 0
Length of ['apple', 'mango', 'orange', 'banana'] is 4
Length of () is 0
Length of (1, 2, 3, 4, 5) is 5

The len() Function with Strings and Bytes

When we use the len() function with a string, it returns the total number of characters in it. While using it with a bytes object returns the total number of bytes in that bytes object. The same is true for the bytes array object. See the example below:

Example 2:

fruit = ''   # Empty String
print('Length of', fruit, 'is', len(fruit))

fruit = 'Apple'
print('Length of', fruit, 'is', len(fruit))

language = b'Python'   # Bytes Object
print('Length of', language, 'is', len(language))

numbers = bytearray([1, 2, 3, 4])   # Bytes Array Object
print('Length of', numbers, 'is', len(numbers))

Output:

Length of  is 0
Length of Apple is 5
Length of b'Python' is 6
Length of bytearray(b'\x01\x02\x03\x04') is 4

The len() Function with Sets and Dictionaries

Using the len() function with a set returns the total number of items in the set. While using it on a dictionary returns the total number of key-value pairs in that dictionary. See the example below:

Example 3:

numbers = {}   # Empty set
print('Length of', numbers, 'is', len(numbers))

numbers = {1, 2, 3, 4}
print('Length of', numbers, 'is', len(numbers))

student = {}   # Empty dictionary
print('Length of', student, 'is', len(student))

student = { 'name': 'John', 'age': 24, 'gender': 'Male'}
print('Length of', student, 'is', len(student))

Output:

Length of {} is 0
Length of {1, 2, 3, 4} is 4
Length of {} is 0
Length of {'name': 'John', 'age': 24, 'gender': 'Male'} is 3

Frequently Asked Questions

Is len() function or method?

Ans:- len() is actually a function, not a method. The len() function calls the inbuilt __len()__ method which returns the length of the object passed to the len() function.


What does __len()__ mean in Python?

Ans:- The __len()__ is an inbuilt python method which is implicitly called by the len() function when calculating the length of the iterable object passed to it.