Loops/Foreach: Difference between revisions

→‎{{header|Python}}: Note and examples about iteration order and sorting of dictionary keys
(→‎{{header|jq}}: JSON objects too)
(→‎{{header|Python}}: Note and examples about iteration order and sorting of dictionary keys)
Line 1,357:
<lang python>for i in collection:
print i</lang>
 
Note: The Python ''<code>for''</code> statement is always a ''"foreach" ...'' and the ''<code>range()''</code> and ''<code>xrange()''</code> built-in functions are used to generate lists of indexes over which it will iterate as necessary. The majority of Python objects support iteration. Lists and tuples iterate over each item, strings iterate over each character, dictionaries iterate over keys, files iterate over lines, and so on.
 
For example:
Line 1,370 ⟶ 1,371:
 
print lines, words, characters</lang>
 
Whether <code>for</code> loops over the elements of the collection in order depends on the collection having an inherent order or not. Elements of strings (i.e. characters), tuples and lists, for example, are ordered but the order of elements in dictionaries and sets is not defined.
 
One can loop over the key/value pairs of a dictionary in ''alphabetic'' or ''numeric'' key order by sorting the sequence of keys, provided that the keys are all of ''comparable'' types. In Python 3.x a sequence of mixed numeric and string elements is not sortable (at least not with the default invocation of <code>sorted()</code>), whereas in Python 2.x numeric types are sorted according to their string representation by default:
 
<lang python>d = {3: "Earth", 1: "Mercury", 4: "Mars", 2: "Venus"}
for k in sorted(d):
print("%i: %s" % (k, d[k]))
 
d = {"London": "United Kingdom", "Berlin": "Germany", "Rome": "Italy", "Paris": "France"}
for k in sorted(d):
print("%s: %s" % (k, d[k]))</lang>
 
{{works with|Python|2.x}}
 
<lang python>d = {"fortytwo": 42, 3.14159: "pi", 23: "twentythree", "zero": 0, 13: "thirteen"}
for k in sorted(d):
print("%s: %s" % (k, d[k]))</lang>
 
=={{header|R}}==
Anonymous user