toastrackengima
toastrackengima

Reputation: 8762

How to perform an operation on all values of a 2D list in Python

I've got a list like so:

counters = [["0"],["0"],["0"],["0"]]

I'd like to perform an operation to each of the inner values - say concatenation, converting to an int and incrementing, etc.

How can I do this for all of the list items; given that this is a multi-dimensional list?

Upvotes: 1

Views: 1619

Answers (4)

dcastello
dcastello

Reputation: 35

If list comprehension scares you, you can use sub-indexing. For example,

for i in range(len(counters)):
    counters[i][0] = str(eval(counters[i][0]) + 1)

counters is a list of lists, therefore you need to access the subindex of 0 (the first item) before you add to it. counters[0][0], for example, is the first item in the first sublist.

Moreover, each of your subitems is a string, not an integer or float. The eval function makes the proper conversion so that we can add 1, and the outer str function converts the final answer back to a string.

Upvotes: 0

Tanveer Alam
Tanveer Alam

Reputation: 5275

>>> counters = [["0"],["0"],["0"],["0"]]
>>> counters = [ [str(eval(i[0])+1)] for element in counters ]
>>> counters
[['1'], ['1'], ['1'], ['1']]

We can use eval function here. About eval() What does Python's eval() do?

Upvotes: 0

Benjamin
Benjamin

Reputation: 2296

  >>> counter=['0']*10
  >>> counter
   ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
  >>> counter=['1']*10
  >>> counter
  ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1']
  overwrite a counter with 1,s

Upvotes: 1

falsetru
falsetru

Reputation: 369494

You can use list comprehension (nested list comprehension):

>>> counters = [["0"],["0"],["0"],["0"]]
>>> [[str(int(c)+1) for c in cs] for cs in counters]
[['1'], ['1'], ['1'], ['1']]

BTW, why do you use lists of strings?

I'd rather use a list of numbers (No need to convert to int, back to str).

>>> counters = [0, 0, 0, 0]
>>> [c+1 for c in counters]
[1, 1, 1, 1]

Upvotes: 4

Related Questions