Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple Subtract statement in Python

using python I am wanting to subtract 256 from a value in the list if a value is greater than 256, but i want the output to be in a tuple format, this is where i need help.

x = [85, 229, 162, 45, 280, 186, 275, 265, 252, 188, 135, 150, 351, 326, 217, 43, 301, 281, 333, 39, 246, 150, 139, 186, 195, 132, 196, 171, 307, 272, 97, 330, 271, 179, 276, 141, 151, 214, 191, 111, 261, 290, 146]

for y in x:
    if y>256:
        print y-256
    else:
        print y 

This code will give the correct output, but in a list format.

like image 546
kyle k Avatar asked Oct 22 '25 00:10

kyle k


2 Answers

To get list use list comprehension / generator expression.

>>> x = [85, 229, 162, 45, 280, 186, 275, 265, 252, 188, 135, 150, 351, 326, 217, 43, 301, 281, 333, 39, 246, 150, 139, 186, 195, 132, 196, 171, 307, 272, 97, 330, 271, 179, 276, 141, 151, 214, 191, 111, 261, 290, 146]
>>> [y - 256 if y > 256 else y for y in x]
[85, 229, 162, 45, 24, 186, 19, 9, 252, 188, 135, 150, 95, 70, 217, 43, 45, 25, 77, 39, 246, 150, 139, 186, 195, 132, 196, 171, 51, 16, 97, 74, 15, 179, 20, 141, 151, 214, 191, 111, 5, 34, 146]
>>> tuple(y - 256 if y > 256 else y for y in x)
(85, 229, 162, 45, 24, 186, 19, 9, 252, 188, 135, 150, 95, 70, 217, 43, 45, 25, 77, 39, 246, 150, 139, 186, 195, 132, 196, 171, 51, 16, 97, 74, 15, 179, 20, 141, 151, 214, 191, 111, 5, 34, 146)
like image 91
falsetru Avatar answered Oct 23 '25 15:10

falsetru


Instead of printing the values, append them to a list:

z = []
for y in x:
    if y>256:
        z.append(y-256)
    else:
        z.append(y)

You can shorten the if/else statement like this:

z = []
for y in x:
    z.append(y-256 if y>256 else y)

And then, you can put all these lines into a list comprehension:

z = [y-256 if y > 256 else y for y in x]
like image 25
Brent Washburne Avatar answered Oct 23 '25 15:10

Brent Washburne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!