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, 
# from  w w w .j  ava2s  .co  m
for x in (1, 2, 3, 4): print(x ** 3, end=' ') 

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

Result

Related Topic