Hanzy
Hanzy

Reputation: 414

Change one-dimensional tuple using slicing / object reassignment

I understand that tuples are immutable objects, however, I know tuples support indexing and slicing. Thus, if I have a tuple assigned to a variable, I can reassign the variable to a new tuple object and change the value at the desired index position.

When I attempt to do this using an index slice, I am getting returned a tuple containing multiple tuples. I understand why this is happening, because I am passing comma separated slices of the original tuple, but I can't figure out how (if possible) I can return a one-dimensional tuple with a single element changed when working with larger sets of data.

Example:

someNumbers = tuple(i for i in range(0, 20))
print(someNumbers)
someNumbers = someNumbers[:10], 2000, someNumbers[11:]
print(someNumbers)

Outputs the following:

(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
((0, 1, 2, 3, 4, 5, 6, 7, 8, 9), 2000, (11, 12, 13, 14, 15, 16, 17, 18, 19))

Can I return a one-dimensional tuple and change only the desired index value?

Upvotes: 0

Views: 65

Answers (2)

Djaouad
Djaouad

Reputation: 22794

You can use tuple concatenation:

someNumbers = tuple(i for i in range(0, 20))
print(someNumbers)
# (2000, ) to differentiate it from (2000) which is a number
someNumbers = someNumbers[:10]+ (2000,) + someNumbers[11:]
print(someNumbers)

Outputs:

(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2000, 11, 12, 13, 14, 15, 16, 17, 18, 19)

Upvotes: 0

glibdud
glibdud

Reputation: 7880

Use concatenation:

someNumbers = someNumbers[:10] + (2000,) + someNumbers[11:]

Upvotes: 1

Related Questions