0% found this document useful (0 votes)
2 views10 pages

List Slicing in Python

IMPORTANT TOPIC

Uploaded by

katwilson2479
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

List Slicing in Python

IMPORTANT TOPIC

Uploaded by

katwilson2479
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

List Slicing in Python

We may have encountered instances in which we needed to access only a portion of


the data, a subset of a text, or a few entries of a list. This is where the idea of
Data Slicing comes into play. The process of accessing a portion/subset of a given
data sequence is known as data slicing. Data slicing can also be used to slice a huge
dataset into smaller bits for faster processing. List slicing is a frequent practice in
Python, and it is the most commonly utilized way for programmers to solve
efficient problems. In this tutorial, you’ll learn how to retrieve specific object
elements and sequences within your lists.

Python List Slicing


List slicing is the process of accessing a specified portion or subset of a list for
some action while leaving the rest of the list alone. Let us consider a Python list. To
access a range of elements in a list, you must slice it. One method is to utilize the
simple slicing operator, i.e. colon (:) With this operator, one can define where to
begin slicing, and where to terminate slicing, and the step. List slicing creates a new
list from an old one.

Syntax

list[start: stop: step]


where,

 start – index position from where the slicing will start in a list
 stop – index position till which the slicing will end in a list
 step – number of steps, i.e. the start index is changed after every n steps, and
list slicing is performed on that index
Note – In Python, indexing starts from 0, and not 1.

Get all the Items


Copy Code

my_list = [1, 3, 5, 7, 9]

print('Items in List are:', my_list[:])


Output

Items in List are: [1, 3, 5, 7, 9]


In the above program, to get all the elements of the list we use ‘:’. This is similar to
the statement print(my_list)

Get all the Items After a Specific Position


Copy Code

my_list = [1, 3, 5, 7, 9, 11, 13, 15]

print('Items in List after 3rd position are:',


my_list[3:])
Output

Items in List after 3rd position are: [7, 9, 11, 13, 15]
In this program, we have used the start parameter by specifying an integer value
that indicates the starting position of the slicing of the list. The elements at index 3
and all the elements after index 3 will be displayed.

Get all the Items Before a Specific Position


Copy Code

my_list = [1, 3, 5, 7, 9, 11, 13, 15]

print('Items in List till 4th index are:', my_list[:4])


Output

Items in List till 4th index are: [1, 3, 5, 7]


In this program, we have used the stop parameter by specifying an integer value that
indicates the ending position of the slicing of a list. The items before index 4 are
sliced in the example. Element on index position 4 is not included.
Get all the Items from One Position to Another
Position
Copy Code

my_list = [1, 3, 5, 7, 9, 11, 13, 15]

print('Items in List from 1st to 6th index are:',


my_list[1:6])
Output

Items in List from 1st to 6th index are: [3, 5, 7, 9, 11]


If you wish to display all the elements between two specific indices, put them
before and after the ‘:’ symbol. In the preceding example, my list[1:6] returns the
elements between the first and sixth positions. The beginning position (i.e. 1) is
included, but the finishing position (i.e. 6) is not.

Get the Items at Specified Intervals


Copy Code

my_list = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

print('Items in List at step of 2 are:', my_list[::2])


Output

Items in List at step of 2 are: [1, 5, 9, 13, 17]


In this type, we have made use of the step parameter for slicing. The step parameter
is an integer value that prints the list elements after specific intervals. For example,
in the above program, we have declared a step of 2. So the elements in the position
of 0, 2, 4, 6, and so on will be printed.

If you want the indexing to begin with the final item, we can use the negative
sign ‘-‘. In the below example, Items at interval 2 beginning with the last index are
sliced.
Copy Code

my_list = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

print('Items in List are:', my_list[::-2])


Output

Items in List are: [19, 15, 11, 7, 3]

Python Get Current Time


Python is a modern programming language that is adaptable, general-purpose, and
high-level. It also has datetime and time modules for performing time-sensitive
activities. The time value begins on January 1st, 1970, and most operating systems
support it until 2038. Working with time is an important aspect of many
applications. Assume you’re creating a sign-up form for a website. You might wish
to get the current time so you know when a user joined your site. This is where the
Python get current time module comes in handy. You can use the time module in
your Python scripts to work with time.

Python Date and Time


Date and time are not data types in Python, however, a module called datetime can
be imported to work with both the date and the time. There is no need to install the
datetime module outside because it is built into Python. In Python, there are
numerous ways to obtain the current date and time by utilizing built-in and third-
party modules.

Methods to get current time


The two techniques for obtaining the current time in Python are as follows:

 By making use of the datetime module

 By employing the time module

Using the datetime module


The datetime module is a built-in Python module. It has a plethora of built-in
capabilities for obtaining the current date and time. The datetime module’s now()
function returns the current time as well as the date. The datetime.now() function
returns the current local time and date. It displays datetime in the YYYY-mm-dd
hh:mm:ss.microseconds format by default.

To import the datetime module we using the following method:

from datetime import datetime

Example 1: Current time using datetime object


Example

Copy Code

# Python program to illustrate Python get current time


# Importing datetime module
from datetime import datetime

# storing the current time in the variable


c = datetime.now()

# Displays Time
current_time = c.strftime('%H:%M:%S')
print('Current Time is:', current_time)
# OR
# Displays Date along with Time
print('Current Date and Time is:', c)
Output

Current Time is: 06:50:10


Current Date and Time is: 2021-09-24 06:50:10.535005
Explanation

To obtain the current date and time, we implement the datetime.now() in the above
program. Then, using the now() method, we obtained a datetime object with the
current date and time. However, we simply want the current time, so we used
strftime(). We then constructed a string indicating the current time using the
datetime.strftime() method. We then use %H to extract hours, %M to extract
minutes, and %S to extract seconds.
Another method to extract current time without using the strftime() method is by
using the time() function. To obtain the current time in seconds since the epoch as a
floating-point value, use the time() function.

Example

Copy Code

# Python program to illustrate Python get current time


# Importing datetime module
from datetime import datetime

# storing the current time in the variable


c = datetime.now().time() # time object

# Displays Time
print('Current Time is:', c)
print('Type(c):', type(c))
Output

Current Time is: 06:57:31.896091


Type(c): <class 'datetime.time'>

Using the time module


You can use the time module to implement a variety of time-related functions in
your Python scripts. The time module is available in all versions of Python. We
must first import it into our program. We may accomplish this with a Python import
statement:

import time
The time module’s localtime() function can be used to determine the current time.
To obtain the current time value, let us utilize the localtime() function in our Python
script.

Example 2: Current time using time module


Example
Copy Code

# Python program to illustrate Python get current time


import time

# Local time has date and time


t = time.localtime()
print('Local Time is ', t)

# Extract the time part


current_time = time.strftime("%H:%M:%S", t)
print('Current time is ', current_time)
Output

Local Time is time.struct_time(tm_year=2021, tm_mon=9,


tm_mday=24,
tm_hour=8, tm_min=12, tm_sec=56, tm_wday=4, tm_yday=267,
tm_isdst=0)
Current time is 08:12:56
Explanation

Using the struct_time attributes, we can obtain the current time value in hour,
minute, and second forms. The tm_hour function returns the hour value. The
tm_min and tm_sec, on the other hand, yield the minutes and seconds values,
respectively.

The following are the values that the struct_time object can store:

 tm_year: the year

 tm_mon: month

 tm_mday: day

 tm_hour: hour

 tm_min: minute

 tm_sec: second

 tm_wday: weekday (0 is Monday)


 tm_yday: year’s day

 tm_isdst: time in daylight savings time

Example 3: Current time of a timezone


When you run the above programs, you will see that they do not provide you with
the current date and time in your timezone. To obtain the date and time for a
specific timezone, now() accepts timezone as an input and returns timezone-
oriented output time. However, these time zones are defined in the pytz library.

Example

Copy Code

# Python program to illustrate Python get current time of


a timezone
from datetime import datetime
import pytz

tz_Mumbai = pytz.timezone('Asia/Kolkata')
datetime_Mumbai = datetime.now(tz_Mumbai)
print('India time:', datetime_Mumbai.strftime('%H:%M:
%S'))

tz_Paris = pytz.timezone('Europe/Paris')
datetime_Paris = datetime.now(tz_Paris)
print('Paris time:', datetime_Paris.strftime('%H:%M:%S'))

tz_Dubai = pytz.timezone('Asia/Dubai')
datetime_Dubai = datetime.now(tz_Dubai)
print('Dubai time:', datetime_Dubai.strftime('%H:%M:%S'))
Output

India time: 13:57:43


Paris time: 10:27:43
Dubai time: 12:27:43

Frequently Asked Questions


Q1. How do I get the current time in Python?

In Python, there are numerous ways to acquire the current time using built-in and
third-party modules. The Python time module includes a number of functions for
determining the current time and performing time-related tasks.

Example

Copy Code

from datetime import datetime


import time

# Method 1
t = time.localtime(time.time())
print('Hours:', t.tm_hour)
print('Minutes:', t.tm_min)
print('Seconds:', t.tm_sec)

# Method 2
now = datetime.now()
print('Current Time:', now.time())

# Method 3
print('Current Time:', time.ctime())
Output

Hours: 11
Minutes: 20
Seconds: 58
Current Time: 11:20:58.694902
Current Time: Fri Sep 24 11:20:58 2021
Q2. How do I get the current date in Python?

The Python Datetime module includes the Date class, which can be used to
represent and manipulate dates. The Gregorian calendar is taken into account by the
Date class.

 Import the datetime module’s date class

 To obtain the current date, use the date.today() function


Example
Copy Code

from datetime import date

today = date.today()
print('Current Date:', today)
Output

Current Date: 2021-09-24


Q3. Why is the pendulum module used for?

Pendulum is another Python tool that may be used to obtain the current time in
various time zones. It is comparable to the pytz module, with the sole difference
being that the pendulum module is faster. But first, we need to install the pendulum
module in Python by using the following command in Terminal:

Copy Code

python3 -m pip install pendulum


Example

Copy Code

from datetime import datetime


import pendulum

Ind = pendulum.timezone('Asia/Kolkata')
NY = pendulum.timezone('America/New_york')

print('Current Time in India:', datetime.now(Ind))


print('Current Time in New York:', datetime.now(NY))
Output

Current Time in India: 2021-09-24 14:16:46.579459+05:30


Current Time in New York: 2021-09-24 04:46:46.621306-
04:00

You might also like