Is there a way to color individual elements in a list in Python?

4.2k Views Asked by At

I would like to color elements in a numpy.ndarray, specifically ones which are of numpy.int64 type.

For example, how do I color each 1 in the following list, say, red?

    L = [1,0,1,0,1]

I have tried using colorama. Here is my code. The result is also included.

from colorama import Fore, Back, Style

L = [i%2 for i in range(6)]

for i in L[::2]:
    L[i] = Fore.RED + str(i)

print(L)

['\x1b[31m1', '\x1b[31m0', '\x1b[31m1', '\x1b[31m0', '\x1b[31m1']
3

There are 3 best solutions below

0
user10340258 On

As far I know we cannot store variables in list as colored variable. colorama only prints the variable in color. So your code will be

from colorama import Fore, Back, Style

L = [i%2 for i in range(6)]

for i in L[::2]:
    L[i] = str(i)

for item in L:print(Fore.RED+ str(item))
print(Style.RESET_ALL)
3
Chrispresso On

Lists don't have a concept of color. Colorama characters understood by your computer to represent values in different color. If you want to make your list print with certain colors you need to print each item in the list.

Let's say you want to make the 1's red:

for i in range(len(L)):
    if L[i] == 1:
        L[i] = Fore.RED + str(L[i]) + Fore.RESET
print(L)
# [0, '\x1b[31m1\x1b[39m', 0, '\x1b[31m1\x1b[39m', 0, '\x1b[31m1\x1b[39m']

print(', '.join(str(item) for item in L))  # Now prints certain items in red and others normal.
0
parseltongue.io On

Use the init() method and set autoreset to True.

from colorama import Fore, init
init(autoreset=True)

L = [i%2 for i in range(6)]
for i,x in enumerate(L):
    if x == 1: L[i] = Fore.RED + str(x)
    else: L[i] = str(x)

for x in L: print(x)