Looping techniques in Python

time to read 1 min | 164 words

Python has multiple techniques for looping over data structures.

Dictionary looping with both key and value can be done using the items() method:

my_dict = {'first': 'a', 'second': 'b'}
for k, v in my_dict.items():
    print(k, v)
# first a
# second b

The enumerate() function allows looping with both index and value through any sequence:

my_list = ['a', 'b']
for i, v in enumerate(my_list):
    print(i, v)
# 0 a
# 1 b

zip() function can be used to pair two or more sequences in order to loop over both of them in parallel:

first_list = ['a', 'b']
second_list = ['one', 'two']
for f, s in zip(first_list, second_list):
    print(f, s)
# a one
# b two

To loop in a sorted order, use the sorted() function:

my_list = ['b', 'c', 'a']
for f in sorted(my_list):
    print(f)
# a
# b
# c

To loop in reverse, pass the sorted list to the reversed() function:

for f in reversed(sorted(set(my_list))):
  print(f)
# c
# b
# a


Related Post:

  1. May 25, 2017 New interesting data structures in Python 3
  2. May 22, 2017 Keyword argument demystify
  3. May 03, 2017 Enhance your tuples
  4. May 02, 2017 Get more with collections!
  5. May 01, 2017 There is more to copying
  6. Apr 30, 2017 Implementing weak references in Python
  7. Apr 26, 2017 Next, Function or Method ?
  8. Apr 24, 2017 Generator Expressions
  9. Apr 23, 2017 Yield Keyword
  10. Apr 21, 2017 What are Generators?
  11. Apr 16, 2017 Lambda Functions in Python
  12. Apr 06, 2017 Function in Python are First-Class Object
  13. Apr 05, 2017 Django 1.11 Release Note a Reading
  14. Apr 03, 2017 One Hell Named JSON
  15. Dec 26, 2016 Queue in Python - Part 3
  16. Nov 02, 2016 Queue in Python - Part 2
  17. Nov 02, 2016 Queue in Python - Part 1
  18. Jun 25, 2016 Enable Spark Context on Your Ipython Notebook
  19. Apr 27, 2015 EAFP Coding Style in Python
  20. Jul 24, 2014 Kompresi CSS menggunakan Python