0

I want to change the first list in the tuple below so as to increment each value by 1.

matrix = [1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]

matrix = [x+1 for x in matrix[0]]

print(matrix)

Upon running that code, I receive a single list [2,3,4,5,6]. I am hoping someone can give me a hint that will make it so that the code returns the rest of the tuple like [2,3,4,5,6],[6,7,8,9,10],[11,12,13,14,15]

Omar N
  • 1,720
  • 2
  • 21
  • 33

3 Answers3

3

You can (ab)use a slice operation, such as:

matrix = [1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]
matrix[0][:] = [n + 1 for n in matrix[0]]
# ([2, 3, 4, 5, 6], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15])

This will in-place replace the first list of the tuple rather than create a new tuple and re-bind the matrix name - for that use wim's answer instead.

Community
  • 1
  • 1
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
2

I realise that it involves reformulating your question, but if you don't want the property of immutability, then just make it a 2D list. Given that you want to be changing these values, you probably do want it to be mutable.

The code would then be:

matrix = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
matrix[0] = [x + 1 for x in matrix[0]]
print(matrix)

Also, I added in some spaces. It's only a little thing, but PEP 8 suggests spaces after commas and around binary operators like +.

Community
  • 1
  • 1
Kyle_S-C
  • 1,107
  • 1
  • 14
  • 31
  • Although the tuple type itself is immutable, its elements may contain mutable elements which can still be modified - depending what the OP wants, it's not necessary to make this a list of lists, instead of a tuple of lists, to make changes to an element. – Jon Clements Mar 18 '15 at 01:01
  • 1
    I agree, but I thought it might be worth questioning the need for a tuple as another possible answer, given that you and wim have provided the other sensible proposals. – Kyle_S-C Mar 18 '15 at 01:02
  • Appears you guessed the OP correctly - have a +1 :p – Jon Clements Mar 18 '15 at 01:11
1

It's a bit tricky, because you actually have a tuple not a 2D list:

>>> matrix = [1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]
>>> ([1 + n for n in matrix[0]],) + matrix[1:]
([2, 3, 4, 5, 6], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15])
wim
  • 338,267
  • 99
  • 616
  • 750