Closed . This question needs details or clarity . It is not currently accepting answers.
for index, data in enumerate(unseenWords):
print("index: "+str(index)+ " data:"+data )
I think it solves your problem.
Accessing the index in 'for' loops?, Iteratiner the index is not recommended if we can iterate over the elements(as done in Method #1). Method #3: Using while loop. For a Python list or tuple object, we can go through it via a for loop, which we call iteration. In Python, iteration is done by for in, whereas in many languages, such as C, iteration lists are done by subscripts, such as below Java code. // Java loop in a list example. for (i=0; i<list.length; i++) { n = list[i]; println(n); }
I'm very used to Java code so I'm expecting i to always be an integer but it doesn't seem to be the case in Python as it returns the actual word when i try purely try printing out the 'i'?
Well, python is not java indeed, so why would you expect it to work the same way ? The behaviour of python's for
loop is documented , and you're supposed to read the doc, aren't you ?
I tried using len as following as a replacement: unseenWords.__len__()
Slightly OT : You're not supposed to call "magicmethods" directly (they only are the support for operators - and operators-like functions - overloading). The proper way is len(unseenWords)
.
But that's when I get the erorr in this title
You didn't bother posting the relevant code (which you should have), but obviously you did something like:
for i in `unseenWords.__len__()`:
# ....
which of course raises this error - what would be the sense of iterating over an integer ? Here again, doing at least the official tutorial would have solved your problem (notice that it's the very next part after the explanation of the for
loop...).
though i'm expecting it to be more like: 1 2 3 4 5 6
Like the vast majority of languages - including Java FWIW -, python uses zero-based indexes - but range()
can take a 'start' argument too so it's not really an issue.
Iterate over a list in Python, Let's see what to do if we want to enumerate a python list. You can iterate over the index and value of an item in a list by using Iterate over the list using while loop. Fist get the size of list. Then iterate using while loop from 0 to len (list) – 1. In each iteration access iTh element. Python. ''' Iterate over the list using while loop ''' i = 0 sizeofList = len (wordList) while i < sizeofList : print (wordList [i]) i += 1. 1.
You are performing a for-each
loop instead of iterating by index.
for i in unseenWords: # for every item in the list unseenWord
print(unseenWords) # you print the actual list
This is the same as for (String i : unseenWords)
in Java (as stated by @ChatterOne in the comments).
If you wanted to print each word you would need to do the following:
for i in unseenWords:
print(i)
If what you want is to print the index of each word then there are some different ways to do it, one of which is the following:
for i in range(len(unseenWords)): # iterate on the range of the size
print(i)
Python Enumerate Explained (With Examples), The following Python code implements this task: Cdegrees = [] for i in Iterating over loop indices is useful when we need to process two lists simultaneously. It’s quite rare to need indexes in Python. If you need to loop over multiple lists at the same time, use zip; If you only need to loop over a single list just use a for-in loop; If you need to loop over a list and you need item indexes, use enumerate; If you find yourself struggling to figure out the best way to loop, try using the cheat sheet above.
some modification in your code, will give you your desire output. please compare below code with yours
unseenWords = ["Cat", "Geography", "Mouse", "Apocalypse", "Hierarchy", "Opaque", "Holocaust"]
for i in range(0,len(unseenWords),1):
print(i)
will give you :
0 1 2 3 4 5 6
just like in java we do
for (int i=0; i<arrayLength; i++)
System.out.println(i);
as because the indexing begins with zero
Loops and lists, In this tutorial, we'll go over how to iterate through list in Python. of integers from the provided start index up to the end index as specified in the argument list. Iterate over the list using List Comprehension and [::-1] wordList[::-1] It will create a temporary revesed list. Let’s use this in List comprehension to iterating over the list in reverse i.e. ''' Iterate over the list using List Comprehension and [::-1] ''' [print (i) for i in wordList[::-1]]
Ways to Iterate Through List in Python, In Python the typical way to iterate over a loop is to use the conventional foreach loop, as lists expose iterators : values = ["Foo", "Bar", "Baz", Iterate over characters of a string in Python In Python, while operating with String, one can do multiple operations on it. Let’s see how to iterate over characters of a string in Python.
Python - Iterate over a list with indexes, for Loops Over a List The most prototypical use of for in loop is over a list. First, range() together with len('penguin') produces a list of indexes for the word: > Python’s range()method can be used in combination with a for loop to traverse and iterate over a list in Python. The range() method basically returns a sequence of integersi.e. it builds/generates a sequence of integers from the provided start index up to the end index as specified in the argument list.
Python 3 Notes: More on for Loops, antipattern to keep a running index while iterating over a list with a for -loop: # HARMFUL: Don't do this for i in range(len(my_items)): print(i, my_items[i]). Sometimes you may need to iterate through a dictionary in Python but want to do it in sorted order. This can be achieved by using sorted(). When you call sorted(iterable), you get a list with the elements of iterable in sorted order. Let’s see how you can use sorted() to iterate through a dictionary in Python when you need to do it in sorted order.
Comments what output are you actually trying to get? Just a list of all indexes in the list? The relevant iterable for that is range(0, len(unseenWords))
for index, i in enumerate(unseenWords):
for ... in ...
is just like for(... : ...)
in javaWhy do you expect to get the index? It's kind of equivalent to Java's for (String i: unseenWords) {
. You wouldn't expect i
to contain the index, right? @bro-grammer line code execution pythontutor.com/… Use string formatting instead of string concatenation: print("index: {} - data: {}".format(index, data))
yes, its a other way. Thanks Or, better, f-strings. I have read the document. I just don't understand it well enough hence why I go here. I don't understand why everyone on platforms like Stackoverflow expects all beginners to fully understand every concept only because they themselves understand it. It's a very selfish attitude. @Aspect and where in your question do you mention that you've read the doc and what part of it you don't understand ? You may want to read this: stackoverflow.com/help/how-to-ask. This being said, if you've read the doc and experimentally verified by yourself that the behaviour you get is the documented one, then I don't really get where your problem is... But print(unseenWords)
doesn't "print said item". My bad, fixing it