Tuple of characters and their corresponding ASCII values in Python
This Python code creates a tuple called char_ascii_pairs, which contains pairs of characters and their corresponding ASCII values from the characters list. Here's how the code works:
- characters = ['a', 'b', 'c', 'd', 'e']: This line initializes a variable named characters and assigns it a list containing five characters.
- char_ascii_pairs = tuple((char, ord(char)) for char in characters): This line of code initializes a variable named char_ascii_pairs and assigns it a tuple created using a generator expression.
- for char in characters: This part of the code sets up a loop that iterates through each character char in the characters list.
- (char, ord(char)): For each character, it creates a tuple containing the character itself char and its corresponding ASCII value obtained using the ord(char) function.
- tuple(...): This surrounds the generator expression and converts the generated pairs of characters and their ASCII values into a tuple.
- print(characters): This line of code prints the original characters list to the console.
- print(char_ascii_pairs): This line of code prints the char_ascii_pairs tuple (which contains pairs of characters and their ASCII values) to the console.
Source Code
characters = ['a', 'b', 'c', 'd', 'e']
char_ascii_pairs = tuple((char, ord(char)) for char in characters)
print(characters)
print(char_ascii_pairs)
Output
['a', 'b', 'c', 'd', 'e']
(('a', 97), ('b', 98), ('c', 99), ('d', 100), ('e', 101))