I want to create following output using print function only once:
1 - Add
2 - Subtract
3 - Divide
4 - Multiply
To do this I am using following piece of code:
> for i in range(1, 5):
> array = ["Add", "Subtract", "Divide", "Multiply"]
> print(f"{i} - array[{i-1}]")
But the output I get is:
1 - array[0]
2 - array[1]
3 - array[2]
4 - array[3]
Could you help me what am I doing wrong? How can I call element of the array inside print function?
You need to move list indexing inside the {}, otherwise array will be interpreted as a string:
print(f"{i} - {array[i-1]}")
But you are using the print function 4 times in your loop. If, as you say, you wish to use print only once, you can unpack a generator expression and use the sep argument:
array = ['Add', 'Subtract', 'Divide', 'Multiply']
print(*(f'{idx} - {val}' for idx, val in enumerate(array, 1)), sep='\n')
What you want is :
print(f"{i} - {array[i-1]}")
But it's always better that you initialize array before loop or else you are creating the same array everytime you run the loop.
So, something like this is more efficient:
array = ["Add", "Subtract", "Divide", "Multiply"]
for i in range(1, 5):
print(f"{i} - {array[i-1]}")
# 1 - Add
# 2 - Subtract
# 3 - Divide
# 4 - Multiply
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With