How to link create a connection between two lists?

Viewed 158

Let's say I have these two lists:

alpha = ['A', 'B', 'C']
nums = ['1', '2', '3']

What I want to do is to assign each element in alpha to each element in nums. Using a for loop, I would do something like:

for i in alpha:
    for n in nums:
        print(f"{i}{n}")

Output:

A1, A2, A3, B1, B2, B3, C1, C2, C3

But what I want is only to assign A to 1, B to 2, and C to 3, without actually creating a list. I want to do this so that when I ask for input, if the user enters A, I can change 1 to a desired number later in the nums list. Let me clarify this by showing the desired result:

Enter letter: A
The new list is [4, 2, 3]

Also, I don't want to make an if loop because in actuality, I am working with a large list. How to implement such a thing?

4 Answers

I think you might be able to use .index()

alpha = ['A', 'B', 'C']
indexOfA = alpha.index('A')
associatedNumber = nums[indexOfA]

You could use a zip in a list comprehension:

alpha = ['A', 'B', 'C']
nums = ['1', '2', '3']

res = [i + j for i, j in zip(alpha, nums)]
print(res)

Another method would be:

for (item1, item2) in zip(alpha, nums):
    sum_list.append(str(item1)+str(item2))

print(sum_list)

Or:

sum_list = [a + b for a, b in zip(list1, list2)]

Take your pick.

For the first part of your question, you can traverse the two lists in parallel using zip:

for i,n in zip(alpha,nums):
    print(f"{i}{n}")

The second part is different. You need to find the index of the letter in the first list to determine which number to update in the second one.

letter = input("Enter letter: ")
index  = alpha.index(letter)
nums[index] = 4  # or whatever calculation you need to figure out what value to use
print("The new list is",nums)

It is unclear from your question, how you select the value you assign the the list at the position of 'A'. It is also unclear whether you want to modify the original nums list of if a separate one needs to be created with the changed value.

Here is my solution:

alpha = ['A', 'B', 'C']
nums = ['1', '2', '3']

for i, letter in enumerate(alpha):
    print(f"{letter}{nums[i]}")

If you want the output as a list, you can use list comprehension:

result = [f"{letter}{nums[i]}" for i, letter in enumerate(alpha)]
Related