Python list from map

How to Transform List Elements with Python map() Function

Summary: in this tutorial, you’ll learn how to use the Python map() function with lists.

Introduction to the Python map() function

When working with a list (or a tuple), you often need to transform the elements of the list and return a new list that contains the transformed element.

Suppose, you want to double every number in the following bonuses list:

bonuses = [100, 200, 300]Code language: Python (python)

To do it, you can use a for loop to iterate over the elements, double each of them, and add it to a new list like this:

bonuses = [100, 200, 300] new_bonuses = [] for bonus in bonuses: new_bonuses.append(bonus*2) print(new_bonuses) Code language: Python (python)
[200, 400, 600]Code language: Python (python)

Python provides a nicer way to do this kind of task by using the map() built-in function.

The map() function iterates over all elements in a list (or a tuple), applies a function to each, and returns a new iterator of the new elements.

The following shows the basic syntax of the map() function:

iterator = map(fn, list)Code language: Python (python)

In this syntax, fn is the name of the function that will call on each element of the list.

In fact, you can pass any iterable to the map() function, not just a list or tuple.

Back to the previous example, to use the map() function, you define a function that doubles a bonus first and then use the map() function as follows:

def double(bonus): return bonus * 2 bonuses = [100, 200, 300] iterator = map(double, bonuses)Code language: Python (python)

Or you make this code more concise by using a lambda expression like this:

bonuses = [100, 200, 300] iterator = map(lambda bonus: bonus*2, bonuses) Code language: Python (python)

Once you have an iterator, you can iterate over the new elements using a for loop.

Or you can convert an iterator to a list by using the the list() function:

bonuses = [100, 200, 300] iterator = map(lambda bonus: bonus*2, bonuses) print(list(iterator)) Code language: Python (python)

More examples of Python map() function with lists

Let’s take some more examples of using the Python map() function with lists.

1) Using the Python map() function for a list of strings

The following example uses the map() function to return a new list where each element is transformed into the proper case:

names = ['david', 'peter', 'jenifer'] new_names = map(lambda name: name.capitalize(), names) print(list(new_names)) Code language: Python (python)
['David', 'Peter', 'Jenifer']Code language: Python (python)

2) Using the Python map() function to a list of tuples

Suppose that you have the following shopping cart represented as a list of tuples:

carts = [['SmartPhone', 400], ['Tablet', 450], ['Laptop', 700]]Code language: Python (python)

And you need to calculate the tax amount for each product with a 10% tax 10%. In addition, you need to add the tax amount to the third element of each item in the list.

Читайте также:  Show hide hidden text html

The return list should be something like this:

[['SmartPhone', 400, 40.0], ['Tablet', 450, 45.0], ['Laptop', 700, 70.0]]Code language: Python (python)

In order to do so, you can use the map() function to create a new element of the list and add the new tax amount to each like this:

carts = [['SmartPhone', 400], ['Tablet', 450], ['Laptop', 700]] TAX = 0.1 carts = map(lambda item: [item[0], item[1], item[1] * TAX], carts) print(list(carts))Code language: Python (python)

Summary

Источник

Python list from map

Last updated: Feb 18, 2023
Reading time · 3 min

banner

# Convert a Map object to a List in Python

Use the list() class to convert a map object to a list.

The list class takes an iterable (such as a map object) as an argument and returns a list object.

Copied!
my_list = ['1.1', '2.2', '3.3'] new_list = list(map(float, my_list)) print(new_list) # 👉️ [1.1, 2.2, 3.3] print(type(new_list)) # 👉️

convert map object to list

We passed a map object to the list() class to convert it to a list.

The list class takes an iterable and returns a list object.

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

# Iterating over a Map object

If you only need to iterate over the map object, use a basic for loop.

Copied!
my_list = ['1.1', '2.2', '3.3'] map_obj = map(float, my_list) for item in map_obj: # 1.1 # 2.2 # 3.3 print(item)

iterating over map object

The item variable gets set to the current map item on each iteration.

# Convert a Map object to a List using iterable unpacking

You can also use the * iterable unpacking operator to convert a map object to a list.

Copied!
my_list = ['1.1', '2.2', '3.3'] new_list = [*map(float, my_list)] print(new_list) # 👉️ [1.1, 2.2, 3.3] print(type(new_list)) # 👉️

convert map object to list using iterable unpacking

The * iterable unpacking operator enables us to unpack an iterable in function calls, in comprehensions and in generator expressions.

Copied!
result = [*(1, 2), *(3, 4), *(5, 6)] print(result) # 👉️ [1, 2, 3, 4, 5, 6]

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

# Using a list comprehension instead of the map() function

An alternative approach would be to directly use a list comprehension.

Copied!
my_list = ['1.1', '2.2', '3.3'] new_list = [float(i) for i in my_list] print(new_list) # 👉️ [1.1, 2.2, 3.3]

using list comprehension instead of map function

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

In the example, we explicitly pass each list item to the float() class instead of doing it implicitly as we did with the map() function.

# Convert a Map object to a List using a for loop

You can also use a for loop to convert a map object to a list.

Copied!
my_list = ['1.1', '2.2', '3.3'] map_obj = map(float, my_list) new_list = [] for item in map_obj: new_list.append(item) print(new_list) # 👉️ [1.1, 2.2, 3.3]

convert map object to list using for loop

We declared a new variable and initialized it to an empty list and used a for loop to iterate over the map object.

On each iteration, we append the current item to the new list.

# Using a for loop instead of the map function

You can also use a for loop as a replacement for the map function.

Copied!
my_list = ['1.1', '2.2', '3.3'] new_list = [] for item in my_list: new_list.append(float(item)) print(new_list) # 👉️ [1.1, 2.2, 3.3]

using for loop instead of map function

We used a for loop to iterate over the list.

On each iteration, we convert the current item to a float and append the result to a new list.

As shown in the previous examples, the same can be achieved using a list comprehension or the map() function.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Convert A Map Object To A List In Python

Convert a Map object to a List in Python

To convert a map object to a list in Python, you can use the list() method or use the iterable unpacking operator “ * “. Follow the article to understand better.

What is the map() function in Python?

In Python, the built-in map() function iterates the elements of an iterable( list, tuple, dict, set,…) through a given function (e.g. chr(),… ) and returns a list of results when it’s done. You use this function when you want to use a single function to convert for all iterable elements. Iterable and function are passed as arguments to map() in Python.

The map() function returns values ​​called map object.

numTuple = (1, 2, 3, 4, 5) resultMap = map(int, numTuple) print(type(resultMap)) #

The problem here is I want to convert a map object to a list.

Convert a map object to a list in Python

Use the list() method

In Python, ‘ list’ is a data type to archive many other types of data and is allowed access to the elements in the ‘list’. A ‘list’ can include data types such as integers, strings, and objects. ‘List’ is mutable even when created. The elements in the ‘list’ are ordered and have a certain number. The elements in ‘list’ are indexed in a sequence, and by default, the first index of the list is 0.

  • list() creates an empty list if no parameters are passed.
  • list() creates a list of elements in the iterable if the iterable is passed as a parameter.
numTuple = (1, 2, 3, 4, 5) resultMap = map(int, numTuple) # Using list() to convert map object to a list resultList = list(resultMap) print(f"resultList: ") print(f"Type of resultList: ")
resultList: [1, 2, 3, 4, 5] Type of resultList:

The example above map() function returns the squared values of the iterable ‘ numTuple ‘. The values [1, 2, 3, 4, 5] are called map objects, and then I take the map object passed in ‘list’ and output ‘list’ to the screen.

Use the iterable unpacking operator “*”

The * is used as the iterable unpacking operator. The advantage of using the * operator is that you can unpack lists and other containers like tuple, string, generator, dict, and set.

numTuple = (1, 2, 3, 4, 5) # Using the * operator to convert map object to list resultList = [*map(int, numTuple)] print(f"resultList: ") print(f"Type of resultList: ")
resultList: [1, 2, 3, 4, 5] Type of resultList:

In the above example, I use the unpacking operator ‘*’ to unpack an iterable in the map() function.

Summary

If you have any questions about how to convert a map object to a list in Python, leave a comment below. I will answer your questions. Thank you for reading!

Maybe you are interested:

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.

Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

Источник

Convert Map Object to List in Python (3 Examples)

TikTok Icon Statistics Globe

Hi! This tutorial will demonstrate how to transform a map object into a list in the Python programming language.

But first, here is a quick overview of the tutorial:

Let’s dive into Python code!

Create Sample Tuple & List Objects

We will create a sample tuple of integers and list of integers, and another list of character string values that we will use in this tutorial. So, in your preferred Python IDE, run the lines of code below.

tuple_obj = (5,10,15,20) my_list = [5,10,15,20] names = ["Andy", "Hillary", "Josh", "Lisa"]

Example 1: Create Map Object from Tuple & Transform to List

In this first example, we will create a custom function that will square any value parsed to it and then iteratively apply that function to the numeric values in our tuple to create a map object using the map() function, which can iterate over both tuples and lists.

def multiply(a): return a ** 2 map_obj = map(multiply, tuple_obj)

We can confirm that it is indeed a map object by running the type() function.

Next, we will turn the map object into a list by running the list() function.

list_obj = list(map_obj) print(list_obj) # [25, 100, 225, 400] print(type(list_obj)) #

As seen above, the list() function converted the map object into a list.

Example 2: Create Map Object from List of Integers & Transform to List

In this second example, we will create a map object with a lambda function that will double any value parsed to it. We will apply that function to “my_list”.

map_obj = map(lambda x: x + x, my_list) print(type(map_obj)) #

Then convert it to a list called list_obj.

list_obj = list(map_obj) print(list_obj) # [10, 20, 30, 40] print(type(list_obj)) #

See, just like in Example 1; the map object was transformed into a list.

Example 3: Create Map Object from List of Character Strings & Transform to List

In this third and final example, we will create a map object from the “names” list that we created formerly using the map() function to make the strings uppercase and then convert that map object into a list.

map_obj = map(str.upper, names) print(type(map_obj)) #

Let’s now transform it into a list!

list_obj = list(map_obj) print(list_obj) # ['ANDY', 'HILARY', 'JOSH', 'LISA'] print(type(list_obj)) #

As we have seen in the 3 examples above, it is very easy to create a map object in Python and convert that object into a list using the list() function.

Video, Further Resources & Summary

Do you need more explanations on how to convert a map object to a list in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

In the video, we explain in some more detail how to convert a map object to a list in Python.

The YouTube video will be added soon.

Furthermore, I encourage you to check out other interesting Python list tutorials on Statistics Globe, starting with these:

This post has shown how to convert a map object to a list in Python. In case you have further questions, you may leave a comment below.

R & Python Expert Ifeanyi Idiaye

This page was created in collaboration with Ifeanyi Idiaye. You might check out Ifeanyi’s personal author page to read more about his academic background and the other articles he has written for the Statistics Globe website.

Источник

Оцените статью