Summing an element of tuple

Hi everyone,
I’m struggling with the following operation: I have an array of Tuple{Int,String) in which I have to increase by 1 the first element of the tuple but it seems doesn’t work in a while cycle; here the solution I implemented

s=Tuple{Float64,String}
for i in 1:n
push!(s, (0.0,“null”) )
end
for i in 1:n
s[ i ][ 1 ]+=1
end

it gives me error on the setindex, how I’m supposed to do this?Thanks everyone

1 Like

Tuple is immutable, you can’t change value in it, also please post you code in code block

```
your code
```

Oh yes, what a stupid error, I suppose have to use another structure :slight_smile:
Thank you so much and sorry for the bad wrong formatting of the code

I would suggest a 1D array, also known as Vector.

I am however struggling to see the use-case. Perhaps there is a better approach to what you are tying to do? Perhaps you would find the enumerate function or a 1:n range useful.

Since a Tuple is an immutable container, you can’t change it’s contents once it’s created. You can get around this by creating a new Tuple with the modified contents.

s = Tuple{Float64,String}[]
for i = 1:n
    push!(s, (0.0, "null"))
end

for i = 1:n
    s[i] = (s[i][1]+1,s[i][2])
end

In rare cases when you have to change the contents after the tuple was created, you can still change the underlying contents of mutable containers inside tuples. But in this case, maybe choosing an Array from the beginning could be better.

s = Tuple{Vector{Float64},String}[]
for i = 1:n
    push!(s, ([0.0],"null"))
end

for i = 1:n
    s[i][1] .+= 1
end
1 Like

BTW, you can simplify this kind of tuple replacement with Base.setindex:

julia> x = (1, 2, 3)
(1, 2, 3)

julia> y = Base.setindex(x, 5, 2)  # Create a new tuple like `x` but with its second entry set to 5
(1, 5, 3)
3 Likes

It’s great to know about such a function; I had no idea it existed because it’s not exported. I usually see it when extending functionality of structs like import Base.setindex; setindex(..) = ...

I think it is a bit confusing, though, because the order of the arguments is not what I would expect. If I’m reading it, I’d compare with the equivalent x[2] = 5, so I’m expecting setindex(x, 2, 5). This is similar to, for example, copyto!(A, Ainds, B, Binds) which means A[Ainds] = B[Binds].

Arguments to setindex are just like getindex, setindex!, view. The index always comes last, because for multi-dimensional objects there will be more than one of them.

2 Likes