mrahma04
mrahma04

Reputation: 129

Confused about list variable assignment

I'm following a book and i ran into this sample program. I'm not sure how the numbers[position] in line 5 is working here? What is the relationship between position and numbers in that variable assignment?

numbers = [1, 3, 5]
position = 0

while position < len(numbers):
    number = numbers[position]
    if number % 2 == 0:
        print "Found even number", number
        break
    position = position + 1

else:
    print "No even number found"

Upvotes: 1

Views: 73

Answers (4)

mrahma04
mrahma04

Reputation: 129

I wasn't familiar with this style of variable assignment. I've seen lists referenced directly using index numbers. But since this post, I've tried the following and it cleared it up. Thank you very much!

list1 = ["apples", "oranges"]
position = 1

output1 = list1[0]
output2 = list1[position]

print output1
print output2

Upvotes: 0

Rockybilly
Rockybilly

Reputation: 4510

That number inside square brackets is an index of the list,

like so

lst = ["b", "c", 3] # Take care not to use "list" as a variable name by the way.
print lst[0]        # I used lst in my example

gives you:

"b"

The first element of the list.

However I could not pass without saying that for loop is a far better way of doing this. Rather than incrementing position one-by-one and telling while loop to stop when it reaches to the length of the list is just good for understanding the concepts. I am sure your textbook is going to cover that next.

Upvotes: 1

J.Doe
J.Doe

Reputation: 23

In number = numbers[position] literally means what it says. position is a position in the list. First it is assigned to zero, so when doing numbers[position] it is actually calling the number in the list at position zero which is 1. Then it does position = position + 1 which will ask it for the number in position 1 in the list and so on.

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155343

It's not variable assignment, it's lookup. position is an index; when it has a value of 0, numbers[position] returns 1 (the first element in numbers), for position 1 it gets 3, etc.

Python sequences like list are indexed 0-up, so the first element in a sequence is at index 0, and the last is at index len(seq) - 1.

Upvotes: 0

Related Questions