Assign Alphabet to Each Element – Python
Last Updated :
29 Jan, 2025
The task of assigning an alphabet to each element in a list involves transforming the elements of the list into corresponding alphabetic characters, where each unique element is mapped to a unique letter. In this task, the goal is to iterate through a list and assign a letter from the alphabet to each unique element based on its first occurrence.
For example, given a list like li = [4, 5, 2, 4, 2, 6, 5, 2, 5], the goal is to convert it into a list of alphabetic characters where each unique number is assigned a letter e.g. {4: ‘a’, 5: ‘b’, 2: ‘c’, 6: ‘d’} , resulting in the transformed list [‘a’, ‘b’, ‘c’, ‘a’, ‘c’, ‘d’, ‘b’, ‘c’, ‘b’].
This method utilizes the itertools.count generator in combination with a defaultdict to assign alphabets dynamically. Count generator increments indices lazily, which means values are only generated when needed.
Python
from collections import defaultdict
from itertools import count
import string
li = [4, 5, 2, 4, 2, 6, 5, 2, 5]
counter = count() # Step 1
temp = defaultdict(lambda: string.ascii_lowercase[next(counter)]) # Step 2
res = [temp[ele] for ele in li] # Step 3
print(res)
Output['a', 'b', 'c', 'a', 'c', 'd', 'b', 'c', 'b']
Explanation:
- count()) creates an infinite iterator that will give the next number every time it is called.
- defaultdict(lambda: string.ascii_lowercase[next(counter)]) creates a dictionary that assigns a letter from the alphabet to each unique element based on the counter’s value.
- [temp[ele] for ele in li] uses a list comprehension to map the elements in li to the corresponding letters, based on their first occurrence in the list.
Using enumerate
Set extract unique elements from the list and enumerate assign sequential alphabet indices. It ensures a deterministic mapping by sorting the unique elements before indexing.
Python
import string
li = [4, 5, 2, 4, 2, 6, 5, 2, 5]
unique_elements = {ele: string.ascii_lowercase[i] for i, ele in enumerate(sorted(set(li)))}
res = [unique_elements[ele] for ele in li]
print(res)
Output['b', 'c', 'a', 'b', 'a', 'd', 'c', 'a', 'c']
Explanation:
- {ele: string.ascii_lowercase[i] for i, ele in enumerate(sorted(set(li)))} converts the list li to a set to remove duplicates, sorts the set and then creates a dictionary that maps each unique element to an alphabet letter .
- List comprehension iterates over the original list li and replaces each element with the corresponding letter from the unique_elements dictionary.
Using dictionary
A straightforward method where a dictionary is used to manually track indices and map elements to alphabets. It iterates through the list and assigns alphabets when new elements are encountered.
Python
import string
li = [4, 5, 2, 4, 2, 6, 5, 2, 5]
temp = {} # Initialize an empty dictionary
index = 0 # Initialize the index
for ele in li: # Iterate over the list `li`
if ele not in temp:
temp[ele] = string.ascii_lowercase[index]
index += 1
res = [temp[ele] for ele in li]
print(res)
Output['a', 'b', 'c', 'a', 'c', 'd', 'b', 'c', 'b']
Explanation:
- if ele not in temp checks if the element is already assigned an alphabet.
- temp[ele] = string.ascii_lowercase[index] assigns the letter corresponding to the current index from string.ascii_lowercase .
- index += 1 increments the index to point to the next letter for the next unique element.
- res = [temp[ele] for ele in li] creates a new list res by mapping each element in li to its assigned alphabet from temp.
Using list comprehension
list comprehension efficiently assign an alphabet to each element in a list. The method combines dictionary operations with conditional checks in a compact and readable one-liner. By using temp.setdefault(), we ensure that each unique element is mapped to an alphabet letter and the index is incremented only when a new element is encountered.
Python
import string
li = [4, 5, 2, 4, 2, 6, 5, 2, 5]
temp = {} # Initialize an empty dictionary
index = 0 # Initialize the index
res = [
temp.setdefault(ele, string.ascii_lowercase[index := index + 1 if ele not in temp else index])
for ele in li
]
print(res)
Output['b', 'c', 'd', 'b', 'd', 'e', 'c', 'd', 'c']
Explanation:
- temp.setdefault(ele, …) for each element in li, it checks if it’s in temp. If not, it assigns an alphabet letter based on the current index.
- string.ascii_lowercase[index := index + 1 if ele not in temp else index] assigns a letter from string.ascii_lowercase and increments the index only when a new element is encountered.
Similar Reads
Access Two Elements at a Time using Python
In this article, we will check how to access two elements at a time from a collection, such as a list or tuple, which can be achieved through various methods. In this discussion, we'll explore different methods to achieve this task in Python. Using Zip ()zip() function in Python allows us to access
2 min read
Assign Ids to Each Unique Value in a List - Python
The task of assigning unique IDs to each value in a list involves iterating over the elements and assigning a unique identifier to each distinct value. Since lists in Python are mutable, the goal is to efficiently assign an ID to each unique element while ensuring that repeated elements receive the
3 min read
Python | Record elements Average in List
Given a list of tuples, write a program to find average of similar tuples in list. Examples: Input: [('Geeks', 10), ('For', 10), ('Geeks', 2), ('For', 9), ('Geeks', 10)] Output: Resultant list of tuples: [('For', 9.5), ('Geeks', 7.333333333333333)] Input: [('Akshat', 10), ('Garg', 10), ('Akshat', 2)
3 min read
Convert Each List Element to Key-Value Pair - Python
We are given a list we need to convert it into the key- value pair. For example we are given a list li = ['apple', 'banana', 'orange'] we need to convert it to key value pair so that the output should be like {1: 'apple', 2: 'banana', 3: 'orange'}. We can achieve this by using multiple methods like
3 min read
Python | Operation to each element in list
Given a list, there are often when performing a specific operation on each element is necessary. While using loops is a straightforward approach, Python provides several concise and efficient methods to achieve this. In this article, we will explore different operations for each element in the list.
3 min read
Python - Assign pair elements from Tuple Lists
Given a tuple list, assign each element, its pair elements from other similar pairs. Input : test_list = [(5, 3), (7, 5), (8, 4)] Output : {5: [3], 7: [5], 8: [4], 4: []} Explanation : 1st elements are paired with respective 2nd elements from all tuples. Input : test_list = [(5, 3)] Output : {5: [3]
7 min read
Append Element to an Empty List In Python
In Python, lists are used to store multiple items in one variable. If we have an empty list and we want to add elements to it, we can do that in a few simple ways. The simplest way to add an item in empty list is by using the append() method. This method adds a single element to the end of the list.
2 min read
Python - Append Multiple elements in set
In Python, sets are an unordered and mutable collection of data type what does not contains any duplicate elements. In this article, we will learn how to append multiple elements in the set at once. Example: Input: test_set = {6, 4, 2, 7, 9}, up_ele = [1, 5, 10]Output: {1, 2, 4, 5, 6, 7, 9, 10}Expla
4 min read
Convert a List to Dictionary Python
We are given a list we need to convert the list in dictionary. For example, we are given a list a=[10,20,30] we need to convert the list in dictionary so that the output should be a dictionary like {0: 10, 1: 20, 2: 30}. We can use methods like enumerate, zip to convert a list to dictionary in pytho
2 min read
Convert set into a list in Python
In Python, sets are unordered collections of unique elements. While they're great for membership tests and eliminating duplicates, sometimes you may need to convert a set into a list to perform operations like indexing, slicing, or sorting. For example, if input set is {1, 2, 3, 4} then Output shoul
3 min read