Andy
Andy

Reputation: 541

Return the next item in a list, given one item

I thought this would be straightforward but after a lot of searching I cannot find the answer. I want to return the next item in a list.

So, in the example below I want to return l4.pkl.

list_numbers = ['l1.pkl', 'l2.pkl', 'l3.pkl', 'l4.pkl', 'l5.pkl', 'l6.pkl']
element = 'l3.pkl'

Upvotes: 1

Views: 739

Answers (5)

AlirezaTomari
AlirezaTomari

Reputation: 71

Easy way Find Index of '13.pkl' with using :

listName.index('base_element')

now for accessing next element you need to choose next index so you should try this :

target_element = listName[listName.index('base_element')+1]

Upvotes: 3

David Meu
David Meu

Reputation: 1545

Use index

(For the last index which will raise IndexError you should make the adjustments):

ist_numbers = [
    "l1.pkl",
    "l2.pkl",
    "l3.pkl",
    "l4.pkl",
    "l5.pkl",
    "l6.pkl",
    "l7.pkl",
    "l8.pkl",
    "l9.pkl",
    "l10.pkl",
]
print(ist_numbers[ist_numbers.index("l5.pkl") + 1])

Output:

l6.pkl

Upvotes: 2

user2390182
user2390182

Reputation: 73450

Here's a fun one, using an iterator:

i = iter(list_numbers)
if element in i:  # lazily moves the iterator forward just far enough
    result = next(i, None)  # None is the default if there are no more elements

Or short with a default value:

result = next(i, None) if element in i else None

Some docs:

Upvotes: 3

CutePoison
CutePoison

Reputation: 5355

Just adding to @David Meus answer

You can do

ist_numbers[min(len(ist_numbers)-1,ist_numbers.index(<element>)+1)]

such that you the last element returns the last element.

Otherwise you can use a try/catch with his answer (wrapped in a function)


def get_next_element(ele,l):
    """
    Returns the next element in the list "l" after the provided element "ele"
    """
    try:
        print(l[l.index(ele) + 1])
    except IndexError:
        raise ValueError(f"'{ele}' is the last element in the list")


get_next_element("l1.pkl",ist_numbers) #"l2.pkl"
get_next_element("l10.pkl",ist_numbers) #ValueError: 'l10.pkl' is the last element in the list

Upvotes: 0

Ayush
Ayush

Reputation: 31

Many ways to solve this. Simple Logic is

  1. Find Index
  2. return arr[Index+1]

You can use any method for finding index.

index = list_numbers.index(element)
return list_numbers[index+1]

Upvotes: 0

Related Questions