Python videos
Advertisement

Iterables: Exercises and Solutions

Fibonacci

Exercise

Define a fibonacci list that corresponds to the Fibonacci series up to 8. Then, use slicing to create two subseries:

  • even_fibonacci, with all numbers at even indices (0, 2, etc.); and
  • odd_fibonacci, with all numbers at odd indices (1, 3, etc.).

Solution

fibonacci = [1, 1, 2, 3, 5, 8]
even_fibonacci = fibonacci[::2]
odd_fibonacci = fibonacci[1::2]
print('Fibonacci at even positions: {0}'.format(even_fibonacci))
print('Fibonacci at odd positions: {0}'.format(odd_fibonacci))

Output:

Fibonacci at even positions: [1, 2, 5]
Fibonacci at odd positions: [1, 3, 8]