Overview

This is a list of basic exercises to allow you to practice utilizing lists and strings in the Python programming language.

Exercises 1: Lists

Given a list, write some Python code to performs the following:

  1. Print every element at an odd index.

  2. Print every odd element.

  3. Print all elements in sorted order.

  4. Print all elements in reversed order.

  5. Print the first and last element.

For example:

numbers = [4, 0, 2, 2, 1, 4, 3, 1, 5]

# E1: Elements at odd index (index and value):
1 0
3 2
5 4
7 1

# E2: Elements with odd value (index and value):
4 1
6 3
7 1
8 5

# E3: Elements in sorted order:
0
1
1
2
2
3
4
4
5

# E4: Elements in reversed order:
5
1
3
4
1
2
2
0
4

# E5:
First Element: 4, Last Element: 5

Solutions

Toggle Solutions

# E1: Elements at odd index (index and value):
for index, value in enumerate(numbers):
    if index % 2:
      print index, value

# E2: Elements with odd value (index and value):
for index, value in enumerate(numbers):
    if value % 2:
      print index, value

# E3: Elements in sorted order:
for number in sorted(numbers):
    print number

# E4: Elements in reversed order:
for number in reversed(numbers):
    print number

# E5: First Element: 4, Last Element: 5
print numbers[0], numbers[-1]

Exercises 2: Strings

For this exercise, choose a lyric from one of your favorite songs and store it as a string variable:

lyric = "They said we're wasting our lives, oh at least we know, that if we die - we lived with passion."

Given a lyric string, write some Python code to performs the following:

  1. Convert the lyric to title-case:

    "They Said We'Re Wasting Our Lives, Oh At Least We Know, That If We Die - We Lived With Passion."
    
  2. Convert all the letters to upper-case:

    "THEY SAID WE'RE WASTING OUR LIVES, OH AT LEAST WE KNOW, THAT IF WE DIE - WE LIVED WITH PASSION."
    
  3. Slice the lyric in half:

    "They said we're wasting our lives, oh at least "
    
  4. Split the lyric into words:

    ['They', 'said', "we're", 'wasting', 'our', 'lives,', 'oh', 'at', 'least', 'we', 'know,', 'that', 'if', 'we', 'die', '-', 'we', 'lived', 'with', 'passion.']
    
  5. Reverse the words in the lyric:

    "passion. with lived we - die we if that know, we least at oh lives, our wasting we're said They"
    

Solutions

Toggle Solutions

# E1: Convert the lyric to title-case
lyric.title()

# E2: Convert all the letters to upper-case
lyric.upper()

# E3: Slice the lyric in half
lyric[:len(lyric)/2]

# E4: Split the lyric into words
lyric.split()

# E5: Reverse the words in the lyric
' '.join(reversed(lyric.split()))