How do I access the index itself for a list like the following?
ints = [8, 23, 45, 12, 78]
When I loop through it using a for
loop, how do I access the loop index, from 1 to 5 in this case?
How do I access the index itself for a list like the following?
ints = [8, 23, 45, 12, 78]
When I loop through it using a for
loop, how do I access the loop index, from 1 to 5 in this case?
This way you can extend a list. Extend means you can add multiple values at a time.
To append this list you have to write the code given below:
This way you can add a single value at a time. If you write
ints.append([1])
so this will create a sub list for this element.Best solution for this problem is use enumerate in-build python function.
enumerate return tuple
first value is index
second value is element of array at that index
You can use the
index
methodEDIT Highlighted in the comment that this method doesn’t work if there are duplicates in
ints
, the method below should work for any values inints
:Or alternatively
if you want to get both the index and the value in
ints
as a list of tuples.It uses the method of
enumerate
in the selected answer to this question, but with list comprehension, making it faster with less code.