Python Lists with Enumerate and unpacking operators

A list can be unpacked with the * operator which is much nicer than using “”.join

The example below also shows how to access an element from a list comprehension where enumerate has been used.

This is helpful where you needed to know the index of the letter in a string

Try the code below and before you run it, see if you can predict the output.


ls = ['a','b','c']
print(*(ls))

ls = ['a','b','c']
print(ls)

string = 'enumerate'
print(*enumerate(string))


mystr="hello"
l =[char for i,char in enumerate(mystr)]
print(l[0])


test_time = 50
steps = [step for step in range(0,test_time+1,10)]
print(*steps)
a b c
['a', 'b', 'c']
(0, 'e') (1, 'n') (2, 'u') (3, 'm') (4, 'e') (5, 'r') (6, 'a') (7, 't') (8, 'e')
h
0 10 20 30 40 50

As you can see, the enumerate function helps to index each char in “hello” and * allows you to unpack a list without the [ and the ]

Previous article

Traits #1

Next article

Factorial example in Rust