[Tutor] Replace nth item with single value in each nested list

Narasimharao Nelluri narasimha928 at gmail.com
Thu May 14 16:39:26 EDT 2020


check below solution.

In [23]: a = [[1, 2], [4, 5], [7, 8], [3, 6]]


In [24]: for out in a:
    ...:     if out[-1] > 5:
    ...:         out[-1] =11
    ...:
    ...:


In [25]: a

Out[25]: [[1, 2], [4, 5], [7, 11], [3, 11]]

In [26]:

Thanks
Narasimha

On Thu, May 14, 2020 at 1:00 PM EK Esawi via Tutor <tutor at python.org> wrote:

> Hi all--
>
>
> Thank you Mats for the help.
>
> On my previous post, I did not state my question accurately. The question
> is how do I replace the 2nd element in each sublist based on a condition?
> For example, replace the 2nd element with 11 in each sublist if it’s
> greater than 5. If a=[[1,2],[4,5],[7,8],[3,6]] then the desired results
> would be  a=[[1,2],[4,5],[7,11],[3,11]]. if possible via list comprehension
>
> Thanks again--EK.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list