It's possible via:
t = ('275', '54000', '0.0', '5000.0', '0.0')
lst = list(t)
lst[0] = '300'
t = tuple(lst)
But if you're going to need to change things, you probably are better off keeping it as a list
It's possible via:
t = ('275', '54000', '0.0', '5000.0', '0.0')
lst = list(t)
lst[0] = '300'
t = tuple(lst)
But if you're going to need to change things, you probably are better off keeping it as a list
Depending on your problem slicing can be a really neat solution:
>>> b = (1, 2, 3, 4, 5)
>>> b[:2] + (8,9) + b[3:]
(1, 2, 8, 9, 4, 5)
>>> b[:2] + (8,) + b[3:]
(1, 2, 8, 4, 5)
This allows you to add multiple elements or also to replace a few elements (especially if they are "neighbours". In the above case casting to a list is probably more appropriate and readable (even though the slicing notation is much shorter).
Changing individual elements in Tuples
Changing tuple to list then changing element in list to another from another list then change back to tuple
Tuples and lists
python replace list values using a tuple - Stack Overflow
Videos
As the title states, I'm curious if there's a way to index elements within a tuple. By this I mean overwrite certain elements in a tuple, without having to re-write the whole tuple. I'm currently working through Python Crash Course, and I often find myself going above and beyond the exercises. In this particular book there is no mention of replacing elements in a tuple . I have tried to look this up before asking, but to no avail.
I saw this method on Stack Overflow, but at this point you may as well re-write the whole tuple:
>>> b = (1, 2, 3, 4, 5) >>> b[:2] + (8,9) + b[3:] (1, 2, 8, 9, 4, 5) >>> b[:2] + (8,) + b[3:] (1, 2, 8, 4, 5)>>> b = (1, 2, 3, 4, 5) >>> b[:2] + (8,9) + b[3:] (1, 2, 8, 9, 4, 5) >>> b[:2] + (8,) + b[3:] (1, 2, 8, 4, 5)
Is there a faster way?
(edit): The book does mention changing the elements in a tuple, but it's basically rewriting the whole tuple.
I'm basically just looking for a way to use something like the .insert() method, instead of rewriting the whole tuple.
The more natural data structure for my_tuple is a dictionary. Consider something like this and use the .get() method:
>>> my_lists = [[3,2,2,3,4,1,3,4], [1,2,3,4,5,6]]
>>> my_tuple_list = [(3,5), (6, 7)]
>>> my_dict = dict(my_tuple_list)
>>> my_dict
{3: 5, 6: 7}
>>> my_lists = [[my_dict.get(x,x) for x in somelist] for somelist in my_lists]
>>> my_lists
[[5, 2, 2, 5, 4, 1, 5, 4], [1, 2, 5, 4, 5, 7]]
Per @Wooble's comment, your code will work if you enumerate.
list_of_lists = [[3,2,2,3,4,1,3,4], [1,3,5,3,4,6,3]]
list_of_tuples = [(3,5), (1,9)]
def tup_replace(mylist, mytuple):
for i, item in enumerate(mylist):
if item == mytuple[0]:
mylist[i] = mytuple[1]
return mylist
then you can just nest that some more to work on a list of list and list of tuples.
for mylist in list_of_lists:
for mytuple in list_of_tuples:
mylist = tup_replace(mylist, mytuple)
print mylist
That said, the dictionary approach is probably better.