1

If I have a list like below:

t = [[221.0, 223.0, 43.4],[32.5, 56.7, 65.4, 54.6]]

How can I add a value to each number? For example, I want to add 1 to each number so the list would look like:

tt = [[222.0, 223.0, 44.4],[33.5, 57.7, 66.4, 55.6]]

Currently, I can write the code to replace the first list with the second list, but I would like to create a new list while keeping the first one as well. Thanks!

1
  • I am sure you might have heard of numpy arrays. In case not, and if you are not forced to use lists, you can convert your lists to array as t = np.array([[221.0, 223.0, 43.4],[32.5, 56.7, 65.4, 54.6]]) and then say tt = t + 1. Commented Jan 31, 2019 at 14:45

2 Answers 2

3

Given that you're using lists, you can use the following nested list comprehension, which returns another nested list with 1 added to each number in the sublists:

[[j + 1 for j in i] for i in t]
[[222.0, 224.0, 44.4], [33.5, 57.7, 66.4, 55.6]]

So simply do:

t = [[221.0, 223.0, 43.4],[32.5, 56.7, 65.4, 54.6]]
tt = [[j + 1 for j in i] for i in t]
Sign up to request clarification or add additional context in comments.

Comments

0

You can create the partial function with the operator add(), which adds one to another number

from functools import partial
from operator import add

add_one = partial(add, 1)
print(add_one(1))
# 2
print(add_one(2))
# 3

and map the function add_one() to each element in the sublist.

t = [[221.0, 223.0, 43.4],[32.5, 56.7, 65.4, 54.6]]

tt = [list(map(add_one, i)) for i in t]
# [[222.0, 224.0, 44.4], [33.5, 57.7, 66.4, 55.6]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.