In this example, we will write a python function that will return the position of the only odd number within the number list. If there is no odd number within that list then the function will return -1 instead.

```def odd_one(arr):
for number in arr:
if number % 2 != 0:
return arr.index(number)
return -1
```

The method above will loop through the number list to determine the position of the only odd number within that number list. If no odd number has been found then the method above will return -1!

That is a simple solution, if you have better idea then leave your comment below.

Announcement:

After a while of rest, I have begun to write again, I am planning to turn this website into a full tech website which will deal with programming, electronic gadget topic, and gaming. Feel free to subscribe to any rss topic which you feel you are interested in to read the latest article for that particular topic.

1. Alex Grönholm says:

One-liner: next((i for i, x in enumerate(arr) if x % 2), -1)

2. Hey, I have a couple of notes for how to approach this problem.

First, this doesn’t find the [i]only[/i] odd number. It finds the [i]first[/i] number.

Second, there’s an opportunity for improvement of the idioms you’re using, as well as improving your algorithm. Let’s dig into this.

[b]Idiom use[/b]

```def odd_one(arr):
for number in arr:
if number % 2 != 0:
return arr.index(number)
return -1
```

When working with conditionals, remember that Python has rules for evaluating whether an expression is true or false. One of the rules is that non-zero values are treated as true. Because if this, you never need to do an explicit comparison with 0 (and indeed, comparing a value to zero goes against Python’s recommended code style).

```def odd_one(arr):
for number in arr:
if number % 2:
return arr.index(number)
return -1
```

[b]Algorithm[/b]

Although Python supports looping through values instead of looping through indexes, it is common to need access to both, like in this exercise. Python built-in `enumerate()` exists for this exact situation. Here’s how to avoid searching through the list twice:

```def odd_one(arr):
for index, number in enumerate(arr):
if number % 2:
return index
return -1
```

Nice!

I recommend reading through Python’s built-in function list, as well as reading through the itertools module. They’re chock full of excellent tools! Have fun!