Create a list of characters and their ASCII values


This Python code takes a string, iterates through its characters, and pairs each character with its ASCII value using a list comprehension. Here's how the code works:

  • string = "Hello, world!": This line initializes a variable named string and assigns it the value "Hello, world!".
  • char_ascii = [(char, ord(char)) for char in string]: This line of code initializes a variable named char_ascii and assigns it the result of a list comprehension.
    • for char in string: This part sets up a loop that iterates through each character char in the string.
    • (char, ord(char)): For each character in the string, this expression creates a tuple containing two elements: the original character char and its ASCII value obtained using the ord() function. The ord() function takes a character as input and returns its corresponding ASCII value.
    • [(char, ord(char)) for char in string]: This is the list comprehension itself. It iterates through the characters in the string, pairs each character with its ASCII value, and includes these pairs (tuples) in the new list.
  • print(string): This line of code prints the original string to the console.
  • print(char_ascii): This line of code prints the char_ascii list to the console.

Source Code

string = "Hello, world!"
char_ascii = [(char, ord(char)) for char in string]
print(string)
print(char_ascii)

Output

Hello, world!
[('H', 72), ('e', 101), ('l', 108), ('l', 108), ('o', 111), (',', 44), (' ', 32), ('w', 119), ('o', 111), ('r', 114), ('l', 108), ('d', 100), ('!', 33)]

Example Programs