Python - variable as list index

python list index
python find index of all occurrences in list
python assign list values to variables
python list methods
python select list elements by index
python index
python list index multiple
python add to list

I'm wondering if this is possible in python. I'm accessing a list in this way:

print list[0]['name']

This is fine. Is there a way to use a variable? I mean:

a="[0]['name']"
print list[a]

Thanks for your suggestions.

Some details:

I have a situation where I have something like this:

a = [{"name":"someone", "age":23}]
print a[0]['name']

But since I need to pass "[0]['name']" as parameter, I'd like to understand if this is possible. Thanks,

cips

In general it is dangerous to use eval but you essentially need to convert your string to perform your indexing.

So first you can get your list as a str using repr

>>> l = [{'name': 'bob'}]
>>> repr(l)
"[{'name': 'bob'}]"

then if you concatenate that with your index operation

>>> a = "[0]['name']"
>>> repr(l) + a
"[{'name': 'bob'}][0]['name']"

then eval the whole thing, it should do the trick

>>> eval(repr(l) + a)
'bob'

Python List Index(), The index() method searches an element in the list and returns its position/index. First, this tutorial will introduce you to lists, and then you will see  index() is an inbuilt function in Python, which searches for given element from start of the list and returns the lowest index where the element appears. Syntax : list_name.index(element, start, end)

This is a simple matter of extracting the indices/keys from the string "[0]['name']" and then using those keys to index the list/dict structure.

data = [{"name":"someone", "age":23}]
keys = "[0]['name']"

# split the string into a list of indices/keys
keys = keys[1:-1].split('][')
# keys = ['0', "'name'"]

# the keys are all strings, so we have to convert
# each individual key to the correct type
import ast
keys = [ast.literal_eval(key) for key in keys]
# keys = [0, 'name']

# now use the list of indices/keys we generated to get the value
value = data
for key in keys:
    value = value[key]

print(value) # output: someone

Python list, index() is an inbuilt function in Python, which searches for given element from start of the list and returns the lowest index where the element appears. Parameters : element - The element whose lowest index will be returned. start (Optional) - The position from where the search begins. Python HOME Python Intro Python Get Started Python Syntax Python Comments Python Variables Python Data Types Python Numbers Python Casting list.index(elmnt

I hope not to be out of context, but maybe you can use a function like this if you can convert s = "[0]['name']" to s = (0, 'name'):

def search_index(obj, itero):
    try:
        return search_index(obj[next(itero)], itero)
    except StopIteration:
        return obj

a = [{"name":"someone", "age":23}]
s = (0, 'name')

result = search_index(a, iter(s))
# >>> result = 'someone'

If you want to convert "[0]['name']" to (0, 'name') you can try this:

import re
reg = re.findall(r'\[(\d*?)\]|\[\'(\w*?)\'\]', "[0]['name']")
s = [int(index[0]) if not index[1] else index[1] for index in reg]
# [0, 'name']

It will convert the indexes to the right type, to work with either list or dicts.

An Introduction to Python Lists, Python has a great built-in list type named "list". use the len() function and square brackets [ ] to access data, with the first element at index 0. Instead, assignment makes the two variables point to the one list in memory. The list index starts with 0 in Python. So, the index value of 1 is 0, 'two' is 1 and 3 is 2. But what if you knew the value you wanted to access but didn't know where it would show up in the list? Or if it even existed in the list?

you can use the function eval('a[0][name]'), it will evaluate the string inside as a python code.

here is the reference: https://docs.python.org/3/library/functions.html#eval

Python Lists | Python Education, Python list method index() returns the lowest index in list that obj appears. Syntax​. Following is the syntax for index() method − list.index(obj). Parameters. obj −  The index () method searches an element in the list and returns its index. In simple terms, the index () method finds the given element in a list and returns its position. If the same element is present more than once, the method returns the index of the first occurrence of the element. Note: Index in Python starts from 0, not 1.

You can use exec command

exec("print(list{})".format(a))

I hope it works

Python List index() Method, Each time through the loop, the variable i is used as an index into the list, printing the Since strings are immutable, Python optimizes resources by making two  The list items are also indexed like array elements of other programming languages. If you want to access the elements of the list variable in Python. You have to use the index operator([]) and the slice operator([:]) of Python. Access List Elements Using Index Operator If you want to get the list elements in the output.

11. Lists, Each time through the loop, the variable i is used as an index into the list, printing Lists that contain consecutive integers are common, so Python provides a  Python | Accessing index and value in list. There are various methods to access the elements of a list, but sometimes we may require to access element along with the index on which it is found. Let’s see all the different way of accessing both index and value in a list. Method #1 : Naive method. This is the most generic method that can be possibly employed to perform this task of accessing the index along with the value of the list elements.

9. Lists, Getting Individual Values in a List with Indexes. Say you have the list ['cat', 'bat', '​rat', 'elephant'] stored in a variable named spam . The Python code spam[0]  By the way, the index variables of list comprehensions are also leaked to the enclosing scope. Or, to be precise, were leaked, before Python 3 came along. Python 3 fixed the leakage from list comprehensions, along with other breaking changes. Make no mistake, changing such behavior is a major breakage in backwards compatibility.

Chapter 4 – Lists, Output of accessing the item at index 0. Python also supports negative indexing. Negative Duration: 7:20 Posted: May 29, 2017 You have to use Python for loop and looping over a list variable and print it in the output. The list variable is the variable whose values are comma separated. All the items are enclosed within the square brackets. To print all the variables, you have to pass the variable as an argument of the print statement.

Comments
  • You need to explain why you need this. Otherwise it can only be accomplished with eval or exec
  • Do you want to use this particular string to index your list, or could the variable have a different value? For example a = [0, 'name']?
  • Please see my edit below.
  • Please, no. Avoiding eval is almost trivial in this case; you can easily parse the string "[0]['name']" into a list like [0, 'name'] and then use those values to index a.
  • Welcome to StackOverflow. Please read How to Answer to write better answers in the future.
  • Please don't advocate the use of eval or exec. It's near-trivial to solve the OP's problem without eval. eval opens a massive security hole in your code for no reason.
  • Please don't advocate the use of eval or exec. It's near-trivial to solve the OP's problem without exec. exec opens a massive security hole in your code for no reason.