Python
int function
list comprehension
type conversion
programming

Call int function on every list element?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Converting every element of a list to an integer is one of the most common Python operations — typically needed when reading data from files, user input, or APIs where numbers arrive as strings. Python provides several approaches: map(), list comprehensions, and loops, each with different readability and performance characteristics.

Method 1: map() Function

The most Pythonic approach for applying a single function to every element:

python
1string_numbers = ['1', '2', '3', '4', '5']
2
3# map() applies int() to each element
4int_numbers = list(map(int, string_numbers))
5print(int_numbers)  # [1, 2, 3, 4, 5]

map(int, iterable) returns a lazy iterator, so wrap it in list() if you need a list.

Method 2: List Comprehension

More readable and flexible:

python
1string_numbers = ['1', '2', '3', '4', '5']
2
3int_numbers = [int(x) for x in string_numbers]
4print(int_numbers)  # [1, 2, 3, 4, 5]

List comprehensions are preferred when you need to add conditions or transformations:

python
1# Convert only valid numbers, skip non-numeric strings
2mixed = ['1', 'hello', '3', '', '5']
3int_numbers = [int(x) for x in mixed if x.isdigit()]
4print(int_numbers)  # [1, 3, 5]
5
6# Convert and filter in one step
7numbers = [int(x) for x in string_numbers if int(x) > 2]
8print(numbers)  # [3, 4, 5]

Method 3: For Loop

Explicit but verbose:

python
1string_numbers = ['1', '2', '3', '4', '5']
2
3int_numbers = []
4for s in string_numbers:
5    int_numbers.append(int(s))
6print(int_numbers)  # [1, 2, 3, 4, 5]

Use a loop when you need error handling per element:

python
1mixed = ['1', 'hello', '3', None, '5']
2int_numbers = []
3for item in mixed:
4    try:
5        int_numbers.append(int(item))
6    except (ValueError, TypeError):
7        pass  # Skip non-convertible items
8print(int_numbers)  # [1, 3, 5]

Common Use Cases

Reading Numbers from Input

python
1# Single line of space-separated numbers
2line = "10 20 30 40 50"
3numbers = list(map(int, line.split()))
4print(numbers)  # [10, 20, 30, 40, 50]
5
6# Multiple lines from stdin
7import sys
8all_numbers = [int(line.strip()) for line in sys.stdin]

Reading from CSV

python
1import csv
2
3with open('data.csv') as f:
4    reader = csv.reader(f)
5    for row in reader:
6        int_row = list(map(int, row))
7        print(int_row)

Converting Float Strings to Int

python
1float_strings = ['1.5', '2.7', '3.9']
2
3# Truncate decimals
4ints = [int(float(x)) for x in float_strings]
5print(ints)  # [1, 2, 3]
6
7# Round instead
8ints = [round(float(x)) for x in float_strings]
9print(ints)  # [2, 3, 4]

Converting Different Bases

python
1# Hex strings to int
2hex_strings = ['0xff', '0x1a', '0x2b']
3ints = [int(x, 16) for x in hex_strings]
4print(ints)  # [255, 26, 43]
5
6# Binary strings to int
7bin_strings = ['1010', '1111', '0001']
8ints = [int(x, 2) for x in bin_strings]
9print(ints)  # [10, 15, 1]

Applying Other Functions

The same patterns work for any function, not just int():

python
1words = ['hello', 'world', 'python']
2
3# str.upper on every element
4upper = list(map(str.upper, words))
5print(upper)  # ['HELLO', 'WORLD', 'PYTHON']
6
7# len on every element
8lengths = list(map(len, words))
9print(lengths)  # [5, 5, 6]
10
11# float on every element
12strings = ['1.1', '2.2', '3.3']
13floats = list(map(float, strings))
14print(floats)  # [1.1, 2.2, 3.3]

Performance Comparison

python
1import timeit
2
3data = [str(i) for i in range(100000)]
4
5# map() — fastest for simple function application
6timeit.timeit(lambda: list(map(int, data)), number=100)  # ~1.8s
7
8# List comprehension — slightly slower
9timeit.timeit(lambda: [int(x) for x in data], number=100)  # ~2.0s
10
11# For loop — slowest
12def loop_convert(data):
13    result = []
14    for x in data:
15        result.append(int(x))
16    return result
17timeit.timeit(lambda: loop_convert(data), number=100)  # ~2.5s

map() is typically 10-20% faster than list comprehensions for simple function calls because it avoids the overhead of the Python for loop.

NumPy Alternative

For large numeric datasets, NumPy is significantly faster:

python
1import numpy as np
2
3string_numbers = ['1', '2', '3', '4', '5']
4arr = np.array(string_numbers, dtype=int)
5print(arr)  # [1 2 3 4 5]

Common Pitfalls

  • ValueError on non-numeric strings: int('hello') raises ValueError. Use try/except or validate with str.isdigit() before converting.
  • int('') fails: Empty strings raise ValueError. Filter them out: [int(x) for x in data if x].
  • int() truncates floats: int(3.9) returns 3, not 4. Use round() if you want rounding.
  • map() returns an iterator: In Python 3, map() returns a lazy iterator, not a list. Wrap in list() if you need indexing or multiple iterations.
  • Negative number strings: int('-5') works correctly, but '-5'.isdigit() returns False. Use try/except for robust validation instead of isdigit().

Summary

  • Use list(map(int, iterable)) for the fastest, cleanest conversion of all elements
  • Use [int(x) for x in iterable] for readability and when adding conditions
  • Use a for loop with try/except when error handling is needed per element
  • map() is ~10-20% faster than list comprehensions for simple function application
  • For large numeric data, use np.array(data, dtype=int) for best performance

Course illustration
Course illustration

All Rights Reserved.