+ 2
Help me with nested sequences(PYTHON)
So I have a nested sequence: stuff = [('verbs', 8, 8, 8, 8), ('bold', 8, 8, 8, 8), ('Legs', 8, 8, 8, 8)] And I want to add 10 to stuff[0][2] How can I? Cause when I try it says tuple doesn't support item assignment!
10 Respuestas
+ 5
stuff[0][2]=tuple(list(stuff[0][2]).append(10))
#one liner solution
+ 7
You can't add values to tuples
+ 6
Convert to list, append 10, convert back to tuple, replace stuff[0][2] with this tuple
+ 5
The list() function!
+ 2
So what do do I do?
Cause the code I am working on is based on nested sequences?
+ 2
Errrrr this is kind of embarrassing😞 but how do you convert a tuple to a list?
+ 2
Thanks a bunch
+ 2
I have no idea how I forgot how to convert!
+ 2
@Pegasus You solution dosent work.
I am not trying to add 10 to the list, I am trying to do this:
stuff = [('verb', 8, 8, 8, 8),('erbs', 8, 8, 8, 8), ('vers', 8, 8, 8, 8)]
stuff[0][1] + 10
And make it:
stuff = [('verb', 18, 8, 8, 8),('erbs', 8, 8, 8, 8), ('vers', 8, 8, 8, 8)]
+ 2
I worked out the code a bit and here's what i have
# This is the new list that you wanted to add
newlist = ['Verb',18,8,8]
# This converts your tuples to a 3 list in a list instead of 3 tuples in a list
stuff = list(map(list, [('verb', 8, 8, 8, 8),('bold', 8, 8, 8, 8), ('legs', 8, 8, 8, 8)]))
# This deletes the first element in your list
del (stuff[0])
# This inserts the 'newlist' to the proper placing
stuff.insert(0, newlist)
# This converts your variable back to 3 tuples in
stuff = list(map(tuple, stuff)) a list
# prints the list with the new list
print(stuff)
You could print in between each block of code just to understand what the code does if you would like to know what it's doing instead of just knowing it's doing it.