Python Tutorial
#!/usr/bin/python list_arr = [10, 20, 30, 40, 50] for index, val in enumerate(list_arr): print("index: %d -> val: %d" % (index, val))Output:
$ python for_enumerate.py index: 0 -> val: 10 index: 1 -> val: 20 index: 2 -> val: 30 index: 3 -> val: 40 index: 4 -> val: 50Even there is an optional parameter in enumerate method to specify the starting index.
#!/usr/bin/python list_arr = [10, 20, 30, 40, 50] # start index is 1 here for index, val in enumerate(list_arr, 1): print("index: %d -> val: %d" % (index, val))Output:
index: 1 -> val: 10 index: 2 -> val: 20 index: 3 -> val: 30 index: 4 -> val: 40 index: 5 -> val: 50
#!/usr/bin/python list_arr = [10, 20, 30, 40, 50] for index in range(len(list_arr)): print("index: %d -> val: %d" % (index, list_arr[index]))Output:
$ python for_range.py index: 0 -> val: 10 index: 1 -> val: 20 index: 2 -> val: 30 index: 3 -> val: 40 index: 4 -> val: 50
#!/usr/bin/python list_arr = [10, 20, 30, 40, 50] for index in xrange(len(list_arr)): print("index: %d -> val: %d" % (index, list_arr[index]))Output:
$ python test_xrange.py index: 0 -> val: 10 index: 1 -> val: 20 index: 2 -> val: 30 index: 3 -> val: 40 index: 4 -> val: 50
Python Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page