Skip to content

RESOURCES / BLOG

How to Get the Index of an Item in a List in Python?

Hi folks,

I’m working on a Python script where I have a list of image filenames, and I want to find the position (index) of a specific image in that list. I heard about the .index() method but I’m not sure how it works exactly.

Could someone explain how to get the index of an item in a list in Python? Also, what happens if the item isn’t in the list? Are there safer ways to handle that?

Thanks in advance!

Great question! Getting the index of an item in a list is a fundamental operation in Python and is extremely useful for tasks like locating images in a gallery, manipulating tag lists, or updating metadata dynamically in systems like Cloudinary.

Let’s dive into how to do this properly and safely, with examples relevant to image management.

The simplest way to get the index of an item in a list is to use the .index() method:

images = ['img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg']

position = images.index('img3.jpg')

print(position)  # Output: 2Code language: PHP (php)
  • .index(item) returns the zero-based index of the first matching item.
  • If the item is not found, Python raises a ValueError.

If you try to get the index of an item that doesn’t exist, like:

images.index('img5.jpg')  # Raises ValueError

Python throws:

ValueError: 'img5.jpg' is not in list

To handle this gracefully, use a try-except block:

try:

    position = images.index('img5.jpg')

    print(f"Found at position {position}")

except ValueError:

    print("Image not found in the list")Code language: PHP (php)

Before calling .index(), you can check if the item exists:

if 'img5.jpg' in images:

    position = images.index('img5.jpg')

    print(f"Found at position {position}")

else:

    print("Image not found")Code language: PHP (php)

Say you want to update the tags for a particular image:

images = ['img1.jpg', 'img2.jpg', 'img3.jpg']

tags = [['sunset'], ['portrait'], ['landscape']]

target = 'img2.jpg'

if target in images:

    idx = images.index(target)

    tags[idx].append('featured')

    print(f"Updated tags for {target}: {tags[idx]}")

else:

    print("Image not found")

# Output: Updated tags for img2.jpg: ['portrait', 'featured']Code language: PHP (php)

Lists can have duplicates. .index() only returns the first occurrence.

If you want all positions where an item occurs:

images = ['img1.jpg', 'img2.jpg', 'img3.jpg', 'img2.jpg', 'img4.jpg']

target = 'img2.jpg'

positions = [i for i, x in enumerate(images) if x == target]

print(positions)  # Output: [1, 3]Code language: PHP (php)

This is useful when images appear multiple times in a dataset or batch.

Sometimes you want to iterate and find index and value simultaneously:

for idx, image in enumerate(images):

    if image == 'img3.jpg':

        print(f"Found {image} at index {idx}")Code language: PHP (php)
TaskCode ExampleNotes
Get the index of an existing itemlist.index(item)Raises ValueError if not found
Check existence firstif item in list: + list.index(item)Avoids errors
Handle missing safelyUse try-except ValueErrorGood for unpredictable input
Find all indices for duplicates[i for i, x in enumerate(list) if x == item]Returns list of positions
Iterate with indexfor idx, val in enumerate(list):Combines index & value

Imagine you maintain a list of Cloudinary public IDs and want to batch update images based on position:

public_ids = ['abc123', 'def456', 'ghi789']

updates = {'def456': {'tags': ['new']}, 'xyz999': {'tags': ['old']}}

for pid in updates:

    if pid in public_ids:

        idx = public_ids.index(pid)

        print(f"Updating {pid} at position {idx}")

        # Call Cloudinary API with public_ids[idx]

    else:

        print(f"{pid} not found in current images")Code language: PHP (php)

If your data structure is more complex, like a list of lists:

image_data = [

    ['img1.jpg', 'sunset'],

    ['img2.jpg', 'portrait'],

    ['img3.jpg', 'landscape']

]

target = 'img2.jpg'

idx = next((i for i, v in enumerate(image_data) if v[0] == target), -1)

print(idx)  # Output: 1Code language: PHP (php)

This finds the index of the sublist where the first element matches the target.

Using .index() is straightforward but requires careful error handling. Whether you’re managing simple lists of images or complex datasets, combining .index() with in checks or exception handling makes your code robust.

Remember:

  • Use try-except or in to avoid crashes.
  • For duplicates, use list comprehensions with enumerate().

Leverage enumerate() to process indices and values together.

Start Using Cloudinary

Sign up for our free plan and start creating stunning visual experiences in minutes.

Sign Up for Free