How to Create a Time Delay in Python

You may use the time package in order to create a time delay in Python:

import time
time.sleep(number of seconds of delay)

Here are few examples of:

3 seconds time delay:

import time
time.sleep(3)

3 minutes time delay:

import time
time.sleep(3 * 60)

Next, you’ll see how to apply a time delay across different scenarios.

Different Scenarios of Time Delay in Python

Scenario 1: Time Delay with a List

Suppose that you created a list in Python with 5 items:

myList = ['aaa','bbb','ccc','ddd','eee']

Let’s now say that your goal is to place 3 seconds time delay before creating, and then printing that list.

You may therefore apply the following syntax in Python to achieve this goal:

import time
time.sleep(3)

myList = ['aaa','bbb','ccc','ddd','eee']
print(myList)

Run the code, and you’ll see the list after 3 seconds:

List

Alternatively, you can place 3 minutes delay (by applying a multiplication of 3 * 60) as captured below:

import time
time.sleep(3 * 60)

myList = ['aaa','bbb','ccc','ddd','eee']
print(myList)

Your list would appear after 3 minutes:

List with 5 items

Scenario 2: Time Delay with a Loop

You can apply a time delay when iterating over a list.

For example, you can print each item in the list every 3 seconds using a loop:

import time

myList = ['aaa','bbb','ccc','ddd','eee']

for i in myList:
    time.sleep(3)
    print(i)

Run the code, and you’ll observe that every 3 seconds an item from the list (from the left to the right) would be printed:

How to Create a Time Delay in Python

Scenario 3: Multiple Time Delays

Let’s now insert 2 time delays in the code:

  • 5 seconds time delay before printing the entire list
  • 3 seconds time delay before printing each item in the list
import time

myList = ['aaa','bbb','ccc','ddd','eee']
time.sleep(5)
print(myList)

for i in myList:
    time.sleep(3)
    print(i)

Once you run the Python code, the entire list would get printed after the first 5 seconds (in red), and then every 3 seconds each item within the list would get printed (in yellow):

How to Create a Time Delay in Python

Scenario 4: Delay with a List Comprehension

You can get the same delay (of 3 seconds to print each item in the list) using a list comprehension:

import time

myList = ['aaa','bbb','ccc','ddd','eee']
myList = [(time.sleep(3), print(i)) for i in myList]

And as before, each item in the list would be printed in intervals of 3 seconds: Time Delay in Python

You may also want to check the following guide that explains how to add a progress bar in Python.