0

so there is something I don't understand about these two loops

If I have a list called numbers

to find the largest number using a for loop I can:

for number in numbers:

    if number > largest:

        largest = number

but why doesn't:

 if number[index] > largest:

     largest = number[index]

work?

and it is the opposite for while loops, so if I want to do something to a list, for example

to replace a value with another, number[index] works and number doesnt work.

1
  • number is the value. List name is numbers and you can only get index of array. Commented Jul 22, 2013 at 11:41

2 Answers 2

1

Because you're already going through each element in the list, not the actual list itself. Thus, you don't need to have the index and access the same element you're already looping with.

>>> for i in range(5):
...     print i
... 
0
1
2
3
4

See how i is not the list but just an individual element in the list? Doing number[index] is just pointless :p

If you want indexes, you can use enumerate:

>>> L = ['one', 'two', 'three']
>>> for i, j in enumerate(L):
...     print i, j, L[i]
... 
0 one one
1 two two
2 three three

As for while loops, well, this isn't the circumstance where you would use one. Use a for-loop ;).

Sign up to request clarification or add additional context in comments.

Comments

0

for number in numbers assign the elements to number one by one. So number here is an element of numbers. If number is really a number. There will be an error using number[i]. This is a syntax of Python. But not for while. You have to use index to access the elements in the list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.