For lists, it will depend on the datatype of each item. It is recommended that all the items have the same data type in the list if you are using sorted.
The result of a sorted() is printable as it returns a list
# Using sorted on a stringexample ='Computer Science!'example_sorted =sorted(example)print('Sorted Version:', example_sorted)for item in example_sorted:print(' -- Current item:', item)
Sorted Version: [' ', '!', 'C', 'S', 'c', 'c', 'e', 'e', 'e', 'i', 'm', 'n', 'o', 'p', 'r', 't', 'u']
-- Current item:
-- Current item: !
-- Current item: C
-- Current item: S
-- Current item: c
-- Current item: c
-- Current item: e
-- Current item: e
-- Current item: e
-- Current item: i
-- Current item: m
-- Current item: n
-- Current item: o
-- Current item: p
-- Current item: r
-- Current item: t
-- Current item: u
# Using sorted on a list of numbers but in reversenumbers = [2,3,5,7,11,13]for number insorted(numbers, reverse=True):print('Current Number:', number)# NOTE: if reverse is not a given argument, it will be assumed as False
Current Number: 13
Current Number: 11
Current Number: 7
Current Number: 5
Current Number: 3
Current Number: 2
The enumerate() function will pair the index for each item in the given sequence argument. This allow us to do a special type of for loop that involves variable unpacking.
The result of enumerate() is not printable
# Using enumerate() with a list of fruitsfruits = ['Apple','Banana','Kiwi','Strawberry']for i, fruit inenumerate(fruits):print('Current index:', i)print('Current fruit:', fruit)if i !=len(fruits)-1:print('--')
Current index: 0
Current fruit: Apple
--
Current index: 1
Current fruit: Banana
--
Current index: 2
Current fruit: Kiwi
--
Current index: 3
Current fruit: Strawberry# enumerate() on a string
# enumerate() on a stringword ='Hello'for i, character inenumerate(word):print(i, character)