0

I have a question. How can I make python script like:

i1 -> hello
i2 -> hi
i3 -> hurra

for (i = 1; i <= 3; i++)
    print(text) 

My desired output:

hello
hi
hurra

So I would like to iterate "links" in function but I want actual "linked values/strings" to iterate in "output". Maybe arrays can be used? Hope I'm clear.

Thanks!

2
  • 2
    What are you calling "i1 ->"? It's not a valid syntax. Is it getting a user input? Making a list of text (need "")? else? Commented Mar 8, 2020 at 22:17
  • 1
    I also have the feeling that what you are trying to do could be implemented in a better way.. What is the context of this? Commented Mar 8, 2020 at 22:20

3 Answers 3

3

Python doesn't have arrays like in C++ or Java. Instead you can use a list.

my_list = ['hello','hi','hurra']

for text in my_list:
    print(text)

There are multiple ways to iterate the list, e.g.:

for i, text in enumerate(my_list):
    print(i, text)

for i in range(0, len(my_list)):
    print(my_list[i])

You could use it like "arrays", but there are many build-in functions that you would find very useful. This is a basic and essential data structure in Python. Most of books or tutorials would cover this topic in the first few chapters.

P.S.: The codes are for Python 3.

Sign up to request clarification or add additional context in comments.

2 Comments

Python's list is the actual counterpart to "arrays" of C++ or Java. And technically, Python does not have an array data type, but it has an array module.
awesome, worked! this second one even on python 2.7
0

You can use dictionaries for this purpose.

mydict={'i1':'hello','i2':'hi','i3':'hurra'}
for i, (key, value) in enumerate(mydict.items()):
    print("index: {}, key: {}, value: {}".format(i, key, value))

Comments

0
x = ['hello', 'hi', 'hurra']

for item in x:
    print(x)

#> hello
#> hi
#> hurra


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.