1

Is it important to use numpy or not? But I tried to use it and didn't succeed.

This is the code:

c = []
a = list(range(10))
c.append(a)
b = list(range(5))
c.append(b)

How to add 1 to all the elements of c?

sophros
  • 14,672
  • 11
  • 46
  • 75
  • Are `a` and `b` supposed to be two different lists? As of now you have a list of two lists, you can use a list comprehension for to add one to each of the elements. If that is the case, see my answer below... – Willie D Feb 14 '19 at 20:12
  • `c` is a list containing 2 lists. "add 1" is not defined for a list. Show `c` and show what result you want. – hpaulj Feb 14 '19 at 20:35

2 Answers2

1

you can do this.

c = [[sum(x) for x in zip(y, [1]*len(y))] for y in c]
Asav Patel
  • 1,113
  • 1
  • 7
  • 25
  • Using the example list in the question this didn't work for me. I got the error: "TypeError: unsupported operand type(s) for +: 'int' and 'list'" – jwalton Feb 14 '19 at 21:03
0

We can use two list comprehensions to do what you desire. The outer loop iterates over the lists in c, and the inner loop iterates over the values in each list of c:

c = []
a = list(range(10))
c.append(a)
b = list(range(5))
c.append(b)

[[val+1 for val in list] for list in c]
jwalton
  • 5,286
  • 1
  • 18
  • 36
  • thanks , i was looking for an straght forward answer like a function or .+ like matlab!!!!! –  Feb 14 '19 at 21:23
  • How would you do this in MATLAB? In Octave I have to make a `cell` of two matrices. But then it complains that the '+' operator is defined for `cell` and `scalar`. – hpaulj Feb 14 '19 at 21:27