python: Sample code patterns for converting int/str type of list elements

Published on:
Last updated:

This post is also available in: 日本語 (Japanese)

I write sample code patterns as a memo, which I often encounter when using python.

Sample code 3 pattern to convert to str type when the list elements are int type

Using the map function

Since the return value of map() is an object, we need to convert it to a list with list().

# sample list that elements are all int
sample_list = [11,22,33,44,55]

# int list elements to string list elements
sample_list = list(map(str, sample_list))
print(sample_list) # ['11', '22', '33', '44', '55']

Using the one-liner(List comprehensions)

One-liner(List comprehensions), which allow functions to be written in a single line, look smart, but can be confusing when writing complex functions.

# sample list that elements are all int
sample_list = [11,22,33,44,55]

# int list elements to string list elements
sample_list = [str(sample_list[x]) for x in range(0,len(sample_list))]
print(sample_list) # ['11', '22', '33', '44', '55']

Using the basic for statements

It is the most basic method, but it is easy to understand, so it is possible to perform complicated processing.

# sample list that elements are all int
sample_list = [11,22,33,44,55]

# int list elements to string list elements
for x in range(0,len(sample_list)):
	sample_list[x] = str(sample_list[x])
print(sample_list) # ['11', '22', '33', '44', '55']

Sample code 3 pattern to convert to int type when the list elements are str type.

Using the map function

Since the return value of map() is an object, we need to convert it to a list with list() .

# sample list that elements are all str
sample_list = ["11","22","33","44","55"]

# str list elements to int list elements
sample_list = list(map(int, sample_list))
print(sample_list) # [11, 22, 33, 44, 55]

Using the one-liner(List comprehensions)

One-liner(List comprehensions), which allow functions to be written in a single line, look smart, but can be confusing when writing complex functions.

# sample list that elements are all str
sample_list = ["11","22","33","44","55"]

# str list elements to int list elements
sample_list = [int(sample_list[x]) for x in range(0,len(sample_list))]
print(sample_list) # [11, 22, 33, 44, 55]

Using the basic for statements

It is the most basic method, but it is easy to understand, so it is possible to perform complicated processing.

# sample list that elements are all str
sample_list = ["11","22","33","44","55"]

# str list elements to int list elements
for x in range(0,len(list(sample_list))):
	sample_list[x] = int(list(sample_list)[x])
print(sample_list) # [11, 22, 33, 44, 55]
No tags for this post.

About
Kuniyoshi Takemoto is the founder of Amelt.net LLC, and editor of this blog(www.amelt.net).Learn more and follow me on LinkedIn.