I want to create a program that gives you the position of the string in a list.
a = [1,3,4,5,6,7,8,9,2,"rick",56,"open"]
I want to create a program that gives you the position of the string in a list.
a = [1,3,4,5,6,7,8,9,2,"rick",56,"open"]
You should read more on operations you can do on Lists here: https://docs.python.org/3/tutorial/datastructures.html#more-on-lists
In this case, you can use the index()
function to get the index of a specific item in the list:
a=[1,3,4,5,6,7,8,9,2,"rick",56,"open"]
print(a.index(7))
print(a.index("rick"))
Output:
5
9
Remember, these indexes are 0-based, so index 5
is actually the 6th element of the list, and index 9 is the 10th element.
If it goes to get all string elements' position:
a=[1,3,4,5,6,7,8,9,2,"rick",56,"open"]
def find_str(arr):
res = {}
for index, value in enumerate(arr):
if isinstance(value, str):
res[value] = index
return res
or just as a shortcut:
def find_str(arr):
return {value:index for index, value in enumerate(arr) if isinstance(value, str)}