• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
[Tut] How to Convert a Float List to an Integer List in Python

How to Convert a Float List to an Integer List in Python

The most Pythonic way to convert a list of floats `fs` to a list of integers is to use the one-liner `fs = [int(x) for x in fs]`. It iterates over all elements in the list `fs` using list comprehension and converts each list element `x` to an integer value using the `int(x)` constructor.

This article shows you the simplest ways to convert a one-dimensional list consisting only of floats to a list of int.

Problem: Given a list of floats `[1.0, 2.0, 3.0]`. How to convert it to a list of ints `[1, 2, 3]`?

The methods are not applicable to lists of lists, they contain rounding errors that are different in each method. If necessary, you can add cycles or define custom functions to check, account for and minimize errors.

## Method 1: List Comprehension

Suppose we have a list:

`a = [1.1, 1.2, 1.8, 0.5, 5.9, -2.3]`

Now, check the type of the list numbers:

```print(type(a[0]))
# <class 'float'>
```

Let’s apply the built-in function `int`, and get a list of integers:

```print([int(a) for a in a])
# [1, 1, 1, 0, 5, -2]
```

Check the type of numbers in the new list:

```A = [int(a) for a in a]
print(type(A[0]))
# <class ‘int’>
```

Thus, using the built-in function `int`, which converts a real number rounds towards zero, or rather, it discards the fractional part, we can get a new list of integers with a one-line code.

## Method 2: Map Function

The built-in function `map` is well optimized and efficient, when it is called, the elements of the list are retrieved upon access. Therefore, one element is stored and processed in memory, which allows the program not to store the entire list of elements in the system memory.

Apply to the same list `a` the following code:

```print(list(map(int, a)))
# [1, 1, 1, 0, 5, -2]
```

It makes no sense to check the type of the elements of the resulting list, since when we called the `map` function, we passed the `int` function already described in method 1 as an argument, and wrapped the result in a list using the `list` function.

The quality of this transformation of the list, or rather the rounding error, is the same as in the first method.

## Method 3: Round & List Comprehension

It is very similar to the first, but unlike `int`, it doesn’t just discard the fractional part but rounds to the nearest even integer if the fractional part is 0.5. You can also pass as the second argument the number of decimal places to which rounding is required, by default it is 0, this is what we will use:

`print([round(a) for a in a])`

Check the type of numbers in the new list:

```D = [round(a) for a in a]
print(type(D[0]))
# <class ‘int’>
```

As you can see from this example, there are different built-in functions to achieve our goal, the difference is in the method and the magnitude of the rounding error.

## Method 4: Math Module

In this way, I suggest using the imported module `math`, in which we will use the three functions `ceil()`, `floor()`, and `trunc()`. let’s take a closer look at each. They have the same syntax, the difference is in the way of rounding.

Let’s apply to the original list:

```a = [1.1, 1.2, 1.8, 0.5, 5.9, -2.3]
print([math.ceil(a) for a in a])
# [2, 2, 2, 1, 6, -2]
```

‘Ceil’ rounds to the next largest integer, respecting the sign(-2.3 < -2 which is True).

Check the type of numbers in the new list:

```C = [math.ceil(a) for a in a]
print(type(C[0]))
# <class ‘int’>
```

Consider the following function in the ‘math’ – ‘floor’ module, which is the opposite of ‘ceil’ – rounding down to the nearest integer:

```print([math.floor(a) for a in a])
# [1, 1, 1, 0, 5, -3]
```

Check the type:

```F = [math.floor(a) for a in a]
print(type(F[0]))
# <class ‘int’>
```

The next function, `trunc()`, is analogous to the built-in function `int()` — it simply discards the fractional part whatever it is:

```print([math.trunc(a) for a in a])
# [1, 1, 1, 0, 5, -2]```

And check the type:

```T = [math.trunc(a) for a in a]
print(type(T[0]))
# <class ‘int’>```

## Method 5: NumPy

Here’s a look at converting a list from an `int` to an array using the NumPy module. The difference between an array and a list is that all elements of an array must be of the same type, like “float” and “int”. Numeric operations with large amounts of data can be performed with arrays much faster and more efficiently than with lists.

Let’s turn our first list `a` into an array:

```import numpy as np
N = np.array(a, int)
```

We pass two arguments to the array function, the name of the list to convert to an array and the type for each element.

`# [ 1 1 1 0 5 -2]`

Сheck the type of elements:

```print(type(N[0]))
# <class 'numpy.int32'>
```

Unlike the `int` number type in Python, the NumPy module defines them slightly differently and is divided into several subgroups. For example, `'int32'` are integers ranging from -2147483648 to 2147483647 (4-byte numbers), `'int64'` are numbers from -9223372036854775808 to 9223372036854775807 (8-byte numbers), there are also different types of `'int'` for 32- and 64-bit operating systems, this must be taken into account when calculating with arrays.

The post How to Convert a Float List to an Integer List in Python first appeared on Finxter.

https://www.sickgaming.net/blog/2020/11/...in-python/

 Possibly Related Threads… Thread Author Replies Views Last Post [Tut] list.clear() vs New List — Why Clearing a List Rather Than Creating a New One? xSicKxBot 0 4 11-30-2020, 09:53 PM Last Post: xSicKxBot [Tut] Python abs() Function xSicKxBot 0 5 11-30-2020, 09:45 AM Last Post: xSicKxBot [Tut] Python Built-In Functions xSicKxBot 0 7 11-29-2020, 08:02 AM Last Post: xSicKxBot [Tut] Show Don’t Tell: Commenting Python Best Practices xSicKxBot 0 7 11-27-2020, 03:41 AM Last Post: xSicKxBot [Tut] How to Catch and Print Exception Messages in Python xSicKxBot 0 7 11-23-2020, 11:45 PM Last Post: xSicKxBot [Tut] Python next() xSicKxBot 0 8 11-22-2020, 08:17 AM Last Post: xSicKxBot [Tut] Python Math Domain Error (How to Fix This Stupid Bug) xSicKxBot 0 11 11-21-2020, 08:01 AM Last Post: xSicKxBot [Tut] Python Int to String with Leading Zeros xSicKxBot 0 20 11-17-2020, 03:22 AM Last Post: xSicKxBot [Tut] Python Function Call Inside List Comprehension xSicKxBot 0 26 11-16-2020, 02:42 AM Last Post: xSicKxBot [Tut] Python TypeError: Object is Not Subscriptable (How to Fix This Stupid Bug) xSicKxBot 0 24 11-13-2020, 12:04 AM Last Post: xSicKxBot

Forum Jump:

 Active Threads [Tut] Premature Optimization is the Root... Last Post: xSicKxBot Today 12:17 AM » Replies: 0 » Views: 0 (Indie Deal) Tropico 6, Capcom & Private... Last Post: xSicKxBot Today 12:16 AM » Replies: 0 » Views: 0 Godot 4 New 2D Features Showcase Last Post: xSicKxBot Today 12:16 AM » Replies: 0 » Views: 0 News - Tenet Finally Gets Theatrical Rel... Last Post: xSicKxBot Today 12:14 AM » Replies: 0 » Views: 1 Microsoft - GitHub to the rescue for dev... Last Post: xSicKxBot Yesterday 06:16 PM » Replies: 0 » Views: 1 News - Light Keepers – Game2Give 2020 Fu... Last Post: xSicKxBot Yesterday 06:16 PM » Replies: 0 » Views: 1 Xbox Wire - This Week on Xbox: November ... Last Post: xSicKxBot Yesterday 06:13 PM » Replies: 0 » Views: 3 News - Tomorrow: Join this live Gamasutr... Last Post: xSicKxBot Yesterday 06:13 PM » Replies: 0 » Views: 49 News - Don’t Miss: Using procedural dest... Last Post: xSicKxBot Yesterday 06:13 PM » Replies: 0 » Views: 50 News - The Giant Dish From James Bond Cl... Last Post: xSicKxBot Yesterday 06:12 PM » Replies: 0 » Views: 43