I need to do in Python the same as:
for (i = 0; i < 5; i++) {cout << i;}
but I don't know how to use FOR in Python to get the index of the elements in a list.
The idea is to count the frequency of each number and then find the number of pairs with equal elements. Suppose, a number x appears k times at index i1, i2,….,ik. Then pick any two indexes ix and iy which will be counted as 1 pair. Similarly, iy and ix can also be pair.
To find the index of an element in a list, you use the index() function. It returns 3 as expected. However, if you attempt to find an element that doesn't exist in the list using the index() function, you'll get an error.
The most straightforward way to get the number of elements in a list is to use the Python built-in function len() . As the name function suggests, len() returns the length of the list, regardless of the types of elements in it.
If you have some given list, and want to iterate over its items and indices, you can use enumerate()
:
for index, item in enumerate(my_list): print index, item
If you only need the indices, you can use range()
:
for i in range(len(my_list)): print i
Just use
for i in range(0, 5): print i
to iterate through your data set and print each value.
For large data sets, you want to use xrange, which has a very similar signature, but works more effectively for larger data sets. http://docs.python.org/library/functions.html#xrange
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With