Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count indexes using "for" in Python

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.

like image 336
Lucas Rezende Avatar asked Mar 01 '12 21:03

Lucas Rezende


People also ask

How do you calculate index count?

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.

How do you find the index of a value in a list Python?

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.

How do you count elements in a list in Python?

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.


2 Answers

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 
like image 151
Sven Marnach Avatar answered Sep 19 '22 14:09

Sven Marnach


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

like image 33
dangerChihuahua007 Avatar answered Sep 22 '22 14:09

dangerChihuahua007