简体   繁体   中英

How could I use the list data type as a parameter in the Python function?

Currently, I started to learn Python. And I've faced an unclear situation.

For example, I have a piece of Java code:

public String myMethod(List<String> listParam, int index) {
String str = listParam.get(index);
return str;
}

The question is - how can/should I do the same thing in Python? Can someone give me the analogy piece of code in Python?

you can try this

def myMethod(list_param, index):
    return list_param[index]

You can use something like this

def myMethod(listParam, index):
    return listParam[index]

you just have to use the index number on the list variable, the example shown below:

# list_variable
name_list = ["foo", "bar", "apple", "orange"]

# using index to get value of respective element 
my_name = name_list[0]
favourite_fruit = name_list[2]

# printing the values
print(my_name)
print(favourite_fruit)

# output
foo
apple

Traditionally Python doesn't declare types of variables. Recent versions support (but don't enforce) static type annotations (see typing module ). The Python interpreter itself doesn't care about the annotations but there are external tools ( mypy ) for checking. Your code would then look like:

from typing import List

def myMethod(listParam: List[str], index: int) -> str:
    s: str = listParam[index]
    return s

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM