Python - For each item in any sequence type

Introduction

For loop can work on any sequence type in Python, including lists, tuples, and strings, like this:

Demo

for x in [1, 2, 3, 4]: print(x ** 2, end=' ')            # In 2.X: print x ** 2, 
#   w  w  w.  j a v a2s. com
for x in (1, 2, 3, 4): print(x ** 3, end=' ') 

for x in 'test': print(x * 2, end=' ')

Result

Related Topic