[Tutor] Replace nth item with single value in each nested list
Mats Wichmann
mats at wichmann.us
Thu May 14 08:47:12 EDT 2020
On 5/14/20 3:16 AM, EK Esawi via Tutor wrote:
> Hi All--
>
> i have a nested list like this a=[[1,2],[4,5],[7,8]]. i want to replace the second element in each nested list with a specific value
> i want something like this [[1,11],[4,11],]7,11]. I tried several things but nothing worked.
> I am hoping for a list comprehension solution
It depends on how well-formed your data is. If it *always* looks like
the above (the items in 'a' are always lists, and always have at least
two elements), then:
for sub in a:
sub[1] = 11
If not consistent, then you have to take a bit more care to deal with
errors.
It also depends on what you want. A list comprehension could be
written, but will give you a new list. Since lists are mutable you have
the change in place option - if you want it.
More information about the Tutor
mailing list