Python equivalents to PHP’s foreach

Unknown Reply 10:50 AM

One of the first problems I had when learning Python was looping over data. PHP’s arrays are very versatile, but in Python, you need to think in terms of lists and dictionaries.

Here’s a cheatsheet for various foreach variants, translated into Python:

Looping over a numeric array (PHP)

$items = array( 'orange', 'pear', 'banana' );

# without indexes
foreach ( $items as $item )
 echo $item;

# with indexes
foreach ( $items as $i => $item )
 echo $i, $item;

Looping over a list (Python)

items = ['orange', 'pear', 'banana']

# without indexes
for item in items:
    print item

# with indexes
for (i, item) in enumerate(items):
    print i, item

Looping over an associative array (PHP)

$continents = array(
 'africa' => 'Africa',
 'europe' => 'Europe',
 'north-america' => 'North America'
);

# without keys
foreach ( $continents as $continent )
 echo $continent;

# with keys
foreach ( $continents as $slug => $title )
 echo $slug, $title;

Looping over a dictionary (Python)

continents = {
    'africa': 'Africa',
    'europe': 'Europe',
    'north-america': 'North America'
}

# without keys
for continent in continents.values():
    print continent

# with keys
for (slug, title) in continents.items():
    print slug, title
Important note: Unlike associative arrays in PHP, Python dictionaries are not ordered.

Bonus

To see all the methods that a list object has, open a python console and typehelp([]). It’s a lot faster than googling for documentation.
For more awesome Python tips, see Code Like a Pythonista: Idiomatic Python.

Related Posts

Python 7062385474497459755
Comments
0 Comments
Facebook Comments by Media Blogger

Post a Comment

Search

Ikuti Channel Youtube Aku Yaa.. Jangan Lupa di subscribe. Terima kasih.

Popular Posts

Translate