Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read array's element inside print function in Python?

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?

like image 251
Hellwishween Avatar asked Jul 26 '26 22:07

Hellwishween


2 Answers

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')
like image 128
jpp Avatar answered Jul 29 '26 11:07

jpp


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                                     
like image 34
Austin Avatar answered Jul 29 '26 13:07

Austin