0% found this document useful (0 votes)
29 views32 pages

Strings and Lists

This document provides an overview of strings in Python, including how to input, store, and manipulate strings through various operations such as slicing, traversing, and using string functions. It explains the concept of immutable strings and demonstrates string creation using different types of quotes, as well as various built-in string methods and constants. Additionally, it covers string operations like concatenation, repetition, and membership testing.

Uploaded by

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

Strings and Lists

This document provides an overview of strings in Python, including how to input, store, and manipulate strings through various operations such as slicing, traversing, and using string functions. It explains the concept of immutable strings and demonstrates string creation using different types of quotes, as well as various built-in string methods and constants. Additionally, it covers string operations like concatenation, repetition, and membership testing.

Uploaded by

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

Chapter 1

Strings

After studying this lesson, students will be able to:


 Learn how Python inputs strings
 Understand how Python stores and uses strings
 Perform slicing operations on strings
 Traverse strings with a loop
 Compare strings and substrings
 Understand the concept of immutable strings
 Understanding string functions.
 Understanding string constants

Introduction
In python, consecutive sequence of characters is known as a string. An individual
character in a string is accessed using a subscript (index). The subscript should always
be an integer (positive or negative). A subscript starts from 0.

Example

# Declaring a string in python

>>>myfirst=“Save Earth”

>>>print myfirst

Save Earth

Let’s play with subscripts

To access the first character of the string

>>>print myfirst[0]

168
To access the fourth character of the string

>>>print myfirst[3]

To access the last character of the string

>>>print myfirst[-1]

>>h

To access the third last character of the string

>>>print myfirst[-3]

Consider the given figure

String A H E L L O

Positive Index 0 1 2 3 4

Negative Index -5 -4 -3 -2 -1

Important points about accessing elements in the strings using subscripts

 Positive subscript helps in accessing the string from the beginning

 Negative subscript helps in accessing the string from the end.

 Subscript 0 or –ve n(where n is length of the string) displays the first element.

Example : A[0] or A[-5] will display „H‟

 Subscript 1 or –ve (n-1) displays the second element.

Note: Python does not support character data type. A string of size 1 can be treated as
characters.

169
Creating and initializing strings
A literal/constant value to a string can be assigned using a single quotes, double quotes
or triple quotes.

 Enclosing the string in single quotes


Example

>>>print („A friend in need is a friend indeed‟)

A friend in need is a friend indeed

Example

>>>print(„ This book belongs to Raghav\’s sister‟)

This book belongs to Raghav‟s sister

As shown in example 2, to include the single quote within the string it should be
preceded by a backslash.

 Enclosing the string in double quotes


Example

>>>print(“A room without books is like a body without a soul.”)

A room without books is like a body without a soul.

 Enclosing the string in triple quote


Example

>>>life=”””\” Live as if you were to die tomorrow.

Learn as if you were to live forever.\”

---- Mahatma Gandhi “””

>>> print life

” Live as if you were to die tomorrow.

Learn as if you were to live forever.”

---- Mahatma Gandhi “””


Triple quotes are used when the text is multiline.

170
In the above example, backslash (\) is used as an escape sequence. An escape
sequences is nothing but a special character that has a specific function. As shown
above, backslash (\) is used to escape the double quote.

Escape sequence Meaning Example

\n New line >>> print “Hot\nCold”


Hot
Cold

Tab space >>>print “Hot\tCold”


Hot
Cold

 By invoking raw_input() method


Let‟s understand the working of raw input() function

Example

>>>raw_input()

Right to education

„Right to education‟

As soon as the interpreter encounters raw_input method, it waits for the user to
key in the input from a standard input device (keyboard) and press Enter key. The
input is converted to a string and displayed on the screen.

Note: raw_input( ) method has been already discussed in previous chapter in detail.

 By invoking input() method

Example

>>>str=input("Enter the string")

Enter the string hello

NameError: name 'hello' is not defined

171
Python interpreter was not able associate appropriate data type with the entered
data. So a NameError is shown. The error can be rectified by enclosing the given
input i.e. hello in quotes as shown below

>>>str=input("Enter the String") >>>str=input("Enter the String")


Enter the String "hello" Enter the String'hello'
>>> print str >>> print str
Hello hello

Strings are immutable


Strings are immutable means that the contents of the string cannot be changed after it is
created.

Let us understand the concept of immutability with help of an example.

Example

>>>str='honesty'

>>>str[2]='p'

TypeError: 'str' object does not support item assignment

Python does not allowthe programmer to change a character in a string. As shown in


the above example, str has the value „honesty‟. An attempt to replace „n‟ in the string by
‟p‟ displays a TypeError.

Traversing a string
Traversing a string means accessing all the elements of the string one after the other by
using the subscript. A string can be traversed using: for loop or while loop.

String traversal using for loop String traversal using while loop

A=‟Welcome‟ A=‟Welcome‟
>>>for i in A: >>>i=0
print i >>>while i<len(A)
W print A[i]

172
e i=i+1
l W
c e
o l
m c
e o
m
e

A is assigned a string literal ‟Welcome‟. A is assigned a string literal „Welcome‟


On execution of the for loop, the i is assigned value 0
characters in the string are printed till the The len() function calculates the length of
end of the string is not reached. the string. On entering the while loop, the
interpreter checks the condition. If the
condition is true, it enters the loop. The
first character in the string is displayed.
The value i is incremented by 1. The loop
continues till value i is less than len-1.
The loop finishes as soon as the value of I
becomes equal to len-1, the loop

Strings Operations

Operator Description Example

+ (Concatenation) The + operator joins the >>> „Save‟+‟Earth‟


text on both sides of the „Save Earth‟
operator
To give a white space between the
two words, insert a space before
the closing single quote of the first
literal.

* (Repetition ) The * operator repeats the >>>3*‟Save Earth ‟

173
string on the left hand side „Save Earth Save Earth Save Earth
times the value on right ‟
hand side.

in (Membership) The operator displays 1 if >>>A=‟Save Earth‟


the string contains the >>> „S‟ in A
given character or the
sequence of characters. True
>>>‟Save‟ in A
True
>>‟SE‟ in A
False

not in The operator displays 1 if >>>‟SE‟ not in „Save Earth‟


the string does not contain True
the given character or the
sequence of characters. >>>‟Save „ not in „Save Earth‟
(working of this operator False
is the reverse of in
operator discussed above)

range (start, stop[, This function is already


step]) discussed in previous
chapter.

Slice[n:m] The Slice[n : m] operator >>>A=‟Save Earth‟


extracts sub parts from the >>> print A[1:3]
strings.
av
The print statement prints the
substring starting from subscript 1
and ending at subscript 3 but not
including subscript 3

174
More on string Slicing
Consider the given figure

String A S A V E E A R T H

Positive Index 0 1 2 3 4 5 6 7 8 9

Negative Index -10 -9 -9 -7 -6 -5 -4 -3 -2 -1

Let‟s understand Slicing in strings with the help of few examples.

Example

>>>A=‟Save Earth‟

>>> print A[1:3]

av

The print statement prints the substring starting from subscript 1 and ending at
subscript 3 .

Example

>>>print A[3:]

„e Earth‟

Omitting the second index, directs the python interpreter to extract the substring till the
end of the string

Example

>>>print A[:3]

Sav

Omitting the first index, directs the python interpreter to extract the substring before
the second index starting from the beginning.

175
Example

>>>print A[:]

„Save Earth‟

Omitting both the indices, directs the python interpreter to extract the entire string
starting from 0 till the last index

Example

>>>print A[-2:]

„th‟

For negative indices the python interpreter counts from the right side (also shown
above). So the last two letters are printed.

Example

>>>Print A[:-2]

„Save Ear‟

Omitting the first index, directs the python interpreter to start extracting the substring
form the beginning. Since the negative index indicates slicing from the end of the string.
So the entire string except the last two letters is printed.

Note: Comparing strings using relational operators has already been discussed in the
previous chapter

String methods & built in functions

Syntax Description Example

len() Returns the length of the >>>A=‟Save Earth‟


string. >>> print len(A)
>>>10

capitalize() Returns the exact copy of the >>>str=‟welcome‟


string with the first letter in

176
upper case >>>print str.capitalize()
Welcome

find(sub[, The function is used to search >>>str='mammals'


start[, end]]) the first occurrence of the >>>str.find('ma')
substring in the given string. It
0
returns the index at which the
substring starts. It returns -1 if On omitting the start parameters,
the substring does occur in the the function starts the search from
string. the beginning.
>>>str.find('ma',2)
3
>>>str.find('ma',2,4)
-1
Displays -1 because the substring
could not be found between the
index 2 and 4-1
>>>str.find('ma',2,5)
3

isalnum() Returns True if the string >>>str='Save Earth'


contains only letters and digit. >>>str.isalnum()
It returns False ,If the string
False
contains any special character
like _ , @,#,* etc. The function returns False as space
is an alphanumeric character.
>>>'Save1Earth'.isalnum()
True

isalpha() Returns True if the string >>> 'Click123'.isalpha()


contains only letters. False
Otherwise return False.
>>> 'python'.isalpha()
True

isdigit() Returns True if the string >>>print str.isdigit()

177
contains only numbers. false
Otherwise it returns False.

lower() Returns the exact copy of the >>>print str.lower()


string with all the letters in „save earth‟
lowercase.

islower() Returns True if the string is in >>>print str.islower()


lowercase. True

isupper() Returns True if the string is in >>>print str.isupper()


uppercase. False

upper() Returns the exact copy of the >>>print str.upper()


string with all letters in WELCOME
uppercase.

lstrip() Returns the string after >>> print str


removing the space(s) on the Save Earth
left of the string.
>>>str.lstrip()
'Save Earth'
>>>str='Teach India Movement'
>>> print str.lstrip("T")
each India Movement
>>> print str.lstrip("Te")
ach India Movement
>>> print str.lstrip("Pt")
Teach India Movement
If a string is passed as argument to
the lstrip() function, it removes
those characters from the left of
the string.

rstrip() Returns the string after >>>str='Teach India Movement‟


removing the space(s) on the >>> print str.rstrip()

178
right of the string. Teach India Movement

isspace() Returns True if the string >>> str=' '


contains only white spaces and >>> print str.isspace()
False even if it contains one
True
character.
>>> str='p'
>>> print str.isspace()
False

istitle() Returns True if the string is >>> str='The Green Revolution'


title cased. Otherwise returns >>> str.istitle()
False
True
>>> str='The green revolution'
>>> str.istitle()
False

replace(old, The function replaces all the >>>str=‟hello‟


new) occurrences of the old string >>> print str.replace('l','%')
with the new string
He%%o
>>> print str.replace('l','%%')
he%%%%o

join () Returns a string in which the >>> str1=('jan', 'feb' ,'mar')


string elements have been >>>str=‟&”
joined by a separator.
>>> str.join(str1)
'jan&feb&mar'

swapcase() Returns the string with case >>> str='UPPER'


changes >>> print str.swapcase()
upper
>>> str='lower'
>>> print str.swapcase()

179
LOWER

partition(sep) The function partitions the >>> str='The Green Revolution'


strings at the first occurrence >>> str.partition('Rev')
of separator, and returns the
('The Green ', 'Rev', 'olution')
strings partition in three parts
i.e. before the separator, the >>> str.partition('pe')
separator itself, and the part ('The Green Revolution', '', '')
after the separator. If the
>>> str.partition('e')
separator is not found, returns
the string itself, followed by ('Th', 'e', ' Green Revolution')
two empty strings

split([sep[, The function splits the string >>>str='The$earth$is$what$we$all


maxsplit]]) into substrings using the $have$in$common.'
separator. The second >>> str.split($,3)
argument is optional and its
SyntaxError: invalid syntax
default value is zero. If an
integer value N is given for the >>> str.split('$',3)
second argument, the string is ['The', 'earth', 'is',
split in N+1 strings. 'what$we$all$have$in$common.']
>>> str.split('$')
['The', 'earth', 'is', 'what', 'we', 'all',
'have', 'in', 'common.']
>>> str.split('e')
['Th', ' Gr', '', 'n R', 'volution']
>>> str.split('e',2)
['Th', ' Gr', 'en Revolution']

Note: In the table given above, len( ) is a built in function and so we don‟t need
import the string module. For all other functions import string statement is required
for their successful execution.

180
Let‟s discuss some interesting strings constants defined in string module:

string.ascii_uppercase

The command displays a string containing uppercase characters.

Example

>>> string.ascii_uppercase

'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

string.ascii_lowercase

The command displays a string containing all lowercase characters.

Example

>>> string.ascii_lowercase

'abcdefghijklmnopqrstuvwxyz'

string.ascii_letters

The command displays a string containing both uppercase and lowercase characters.

>>> string.ascii_letters

'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

string.digits

The command displays a string containing digits.

>>> string.digits

'0123456789'

string.hexdigits

The command displays a string containing hexadecimal characters.

>>> string.hexdigits

'0123456789abcdefABCDEF'

181
string.octdigits

The command displays a string containing octal characters.

>>> string.octdigits

'01234567'

string.punctuations

The command displays a string containing all the punctuation characters.

>>> string.punctuations

'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}-'

string.whitespace

The command displays a string containing all ASCII characters that are considered
whitespace. This includes the characters space, tab, linefeed, return, formfeed, and
vertical tab.

>>> string.whitespace

'\t\n\x0b\x0c\r '

string.printable

The command displays a string containing all characters which are considered printable
like letters, digits, punctuations and whitespaces.

>>> string.printable

'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!
"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}- \t\n\r\x0b\x0c'

Note: Import string module to get the desired results with the commands mentioned
above.

182
Programs using string functions and operators

1. Program to check whether the string is a palindrome or not.

defpalin():

str=input("Enter the String")

l=len(str)

p=l-1

index=0

while (index<p):

if(str[index]==str[p]):

index=index+1

p=p-1

else:

print "String is not a palidrome"

break

else:

print "String is a Palidrome"

2. Program to count no of ‘p’ in the string pineapple.

def lettercount():

word = 'pineapple'

count = 0

for letter in word:

if letter == 'p':

count = count + 1

print(count)

183
Regular expressions and Pattern matching
A regular expression is a sequence of letters and some special characters (also called
meta characters). These special characters have symbolic meaning. The sequence
formed by using meta characters and letters can be used to represent a group of
patterns.

Let‟s start by understanding some meta characters.

For example

str= “Ram$”

The pattern “Ram$” is known as a regular expression. The expression has the meta
character „$‟. Meta character „$‟ is used to match the given regular expression at the end
of the string. So the regular expression would match the string „SitaRam‟ or „HeyRam‟
but will not match the string „Raman‟.

Consider the following codes:

def find(): def find():


import re import re

string1='SitaRam' string1='SitaRam'
if if re.search('Sita$',string1):
re.search('Ram$',string1): print "String Found"
print "String Found" else :
else : print" No Match"
print" No Match" Output
Output: No Match
String Found

As shown in the above examples, Regular expressions can be used in python for
matching a particular pattern by importing the re module.

Note: re module includes functions for working on regular expression.

184
Now let‟s learn how the meta characters are used to form regular expressions.

S.No Meta Usage Example


character

1 [] Used to match a set of characters. [ram]


The regular expression
would match any of the
characters r, a, or m.
[a-z]
The regular expression
would match only
lowercase characters.

2 ^ Used to complementing a set of [^ram]


characters The regular expression
would match any other
characters than
r, a or m.

3 $ Used to match the end of string Ram$


only The regular expression
would match Ram in
SitaRam but will not match
Ram in Raman

4 * Used to specify that the previous wate*r


character can be matched zero or The regular expression
more times. would match strings like
watr, wateer, wateeer and
so on.

5 + Used to specify that the previous wate+r


character can be matched one or The regular expression
more times. would match strings like
water, wateer, wateeer and
so on.

185
6 ? Used to specify that the previous wate?r
character can be matched either The regular expression
once or zero times would only match strings
like watr or water

7 {} The curly brackets accept two wate{1,4}r


integer value s. The first value The regular expression
specifies the minimum no of would match only strings
occurrences and second value water, wateer, wateeer or
specifies the maximum of wateeeer
occurrences

Let‟s learn about few functions from re module

re.compile()
The re.compile( ) function will compile the pattern into pattern objects. After the
compilation the pattern objects will be able to access methods for various operations
like searching and subsitutions

Example

import re

p=re.compile(„hell*o‟)

re.match()
The match function is used to determine if the regular expression (RE) matches at the
beginning of the string.

re.group()

The group function is used to return the string matched the RE

Example

>>>P=re.compile(„hell*o‟)

>>>m=re.match(„hell*o‟, „ hellooooo world‟)

>>>m.group()

„hello‟

186
re.start()

The start function returns the starting position of the match.

re.end()

The end function returns the end position of the match.

re.span()

The span function returns the tuple containing the (start, end) positions of the match

Example

>>> import re

>>> P=re.compile('hell*o')

>>> m=re.match('hell*o', 'hellooooo world')

>>> m.start()

>>> m.end()

>>> m.span()

(0, 5)

re.search()
The search function traverses through the string and determines the position where the
RE matches the string

Example

>>> m=re.search('hell*o', 'favorite words hellooooo world')

>>> m.start()

15

>>> m.end()

187
20

>>> m.group()

'hello'

>>> m.span()

(15, 20)

Re.findall()
The function determines all substrings where the RE matches, and returns them as a list.

Example

>>> m=re.findall('hell*o', 'hello my favorite words hellooooo world')

>>> m

['hello', 'hello']

re.finditer()

The function determines all substrings where the RE matches, and returns them as an
iterator.

Example

>>> m=re.finditer('hell*o', 'hello my favorite words hellooooo world')

>>> m

<callable-iterator object at 0x0000000002E4ACF8>

>>> for match in m:

print match.span()

(0, 5)

(24, 29)

As shown in the above example, m is a iterator. So m is used in the for loop.

188
Script 1: Write a script to determine if the given substring is present in the string.

def search_string():
import re
substring='water'
search1=re.search(substring,'Water water everywhere but not a drop to drink')
if search1:
position=search1.start()
print "matched", substring, "at position", position
else:
print "No match found"

Script 2: Write a script to determine if the given substring (defined using meta
characters) is present in the given string

def metasearch():
import re
p=re.compile('sing+')
search1=re.search(p,'Some singers sing well')
if search1:
match=search1.group()
index=search1.start()
lindex=search1.end()
print "matched", match, "at index", index ,"ending at" ,lindex
else:
print "No match found"

189
EXERCISE

1. Input a string “Green Revolution”. Write a script to print the string in reverse.

2. Input the string “Success”. Write a script of check if the string is a palindrome or
not

3. Input the string “Successor”. Write a script to split the string at every occurrence of
the letter s.

4. Input the string “Successor”. Write a script to partition the string at the occurrence
of the letter s. Also Explain the difference between the function split( ) and
partition().

5. Write a program to print the pyramid.

22

333

4444

55555

6. What will be the output of the following statement? Also justify for answer.

>>> print 'I like Gita\'s pink colour dress'.

7. Give the output of the following statements

>>> str='Honesty is the best policy'

>>> str.replace('o','*')

8. Give the output of the following statements

>>> str='Hello World'

>>>str.istiltle()

9. Give the output of the following statements.

>>> str="Group Discussion"

>>> print str.lstrip("Gro")

190
10. Write a program to print alternate characters in a string. Input a string of your own
choice.

11. Input a string „Python‟. Write a program to print all the letters except the letter‟y‟.

12. Consider the string str=”Global Warming”

Write statements in python to implement the following

a) To display the last four characters.

b) To display the substring starting from index 4 and ending at index 8.

c) To check whether string has alphanumeric characters or not.

d) To trim the last four characters from the string.

e) To trim the first four characters from the string.

f) To display the starting index for the substring „Wa‟.

g) To change the case of the given string.

h) To check if the string is in title case.

i) To replace all the occurrences of letter „a‟ in the string with „*‟

13. Study the given script

def metasearch():

import re

p=re.compile('sing+')

search1=re.search(p,'Some singers sing well')

if search1:

match=search1.group()

index=search1.start()

lindex=search1.end()

print "matched", match, "at index", index ,"ending at", lindex

else:

191
print "No match found"

What will be the output of the above script if search() from the re module is
replaced by match () of the re module. Justify your answer

14. What will be the output of the script mentioned below? Justify your answer.

def find():

import re

p=re.compile('sing+')

search1=p.findall('Some singer sing well')

print search1

15. Rectify the error (if any) in the given statements.

>>> str="Hello World"

>>> str[5]='p'

192
Chapter 2
Lists

After studying this lesson, students will be able to:


 Understand the concept of mutable sequence types in Python.
 Appreciate the use of list to conveniently store a large amount of data in memory.
 Create, access & manipulate list objects
 Use various functions & methods to work with list
 Appreciate the use of index for accessing an element from a sequence.

Introduction
Like a String, list also is sequence data type. It is an ordered set of values enclosed in
square brackets []. Values in the list can be modified, i.e. it is mutable. As it is set of
values, we can use index in square brackets [] to identify a value belonging to it. The
values that make up a list are called its elements, and they can be of any type.

We can also say that list data type is a container that holds a number of elements in a
given order. For accessing an element of the list, indexing is used.

Its syntax is:

Variable name [index] (variable name is name of the list).

It will provide the value at „index+1‟ in the list. Index here, has to be an integer value-
which can be positive or negative. Positive value of index means counting forward from
beginning of the list and negative value means counting backward from end of the list.
Remember the result of indexing a list is the value of type accessed from the list.

Index value Element of the list

0, -size 1st

1, -size +1 2nd

193
2, -size +2 3rd

.
.
.

size -2, -2 2nd last

size -1, -1 last

Please note that in the above example size is the total number of elements in the list.

Let‟s look at some example of simple list:

i) >>>L1 = [1, 2, 3, 4] # list of 4 integer elements.

ii) >>>L2 = [“Delhi”, “Chennai”, “Mumbai”] #list of 3 string elements.

iii) >>>L3 = [ ] # empty list i.e. list with no element

iv) >>>L4 = [“abc”, 10, 20] # list with different types of elements

v) >>>L5 = [1, 2, [6, 7, 8], 3] # A list containing another list known as


nested list

You will study about Nested lists in later parts of the chapter.

To change the value of element of list, we access the element & assign the new value.

Example

>>>print L1 # let‟s get the values of list before change

>>> L1 [2] = 5

>>> print L1 # modified list

[1, 2, 5, 4]

Here, 3rd element of the list (accessed using index value 2) is given a new value, so
instead of 3 it will be 5.

State diagram for the list looks like:

194
L1 0 1 L2 0 Delhi L3

1 2 1 Chennai

2 3 2 Mumbai
3 4

Note: List index works the same way as String index, which is:
 An integer value/expression can be used as index.
 An Index Error appears, if you try and access element that does not exist in the
list.
 An index can have a negative value, in that case counting happens from the end
of the list.

Creating a list
List can be created in many ways:

i) By enclosing elements in [ ], as we have done in above examples.

ii) Using other Lists

Example

L5=L1 [:]

Here L5 is created as a copy of L1.

>>>print L5

L6 = L1 [0:2]

>>>print L6

will create L6 having first two elements of L1.

iii) List comprehension

Example

>>>n = 5

195
>>>l = range(n)

>>>print l

[0, 1, 2, 3, 4]

Example

>>> S= [x**2 for x in range (10)]

>>> print S

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

In mathematical terms, S can be defined as S = {x2 for: x in (0.....9)}. So, we can say
that list comprehension is short-hand for creating list.

Example

>>> A = [3, 4, 5]

>>> B = [value *3 for value in A]

Here B will be created with the help of A and its each element will be thrice of
element of A.

>>> print B

[9, 12, 15]

Comprehensions are functionally equivalent to wrting as:

>>>B = [ ]

>>>for i in A

B. append (i*3)

Similarly, other comprehensions can be expended.

Example

>>> print B

[9, 12, 15]

Let‟s create a list of even numbers belonging to „S‟ list:

>>>C = [i for i in S if i % 2 = = 0]

196
>>>print C

[0, 4, 16, 36, 64]

iv) Using built-in object

L = list ( ) will create an empty list

Example

>>>l = list ( )

>>>print l

[ ] # empty list

Or

L = list (sequence)

Example

>>>L = list [(1, 2, 3, 4)]

>>>print L

[1, 2, 3, 4]

A single new list is created every time, you execute [ ]. We have created many
different lists each using [ ]. But if a list is assigned to another variable, a new list
is not created.

i) A=B=[ ]

Creates one list mapped to both A & B

Example

>>>A = B = [10, 20, 30]

>>> print A, B

[10, 20, 30] [10, 20, 30]

ii) A=[]

B=A

Will also create one list mapped to both

197
Example

>>> A = [1, 2, 3]

>>> B = A

>>> print A, B

[1, 2, 3] [1, 2, 3]

Accessing an element of list


For accessing an element, we use index and we have already seen example doing so. To
access an element of list containing another list, we use pair of index. Lets access
elements of L5 list. Also a sub-list of list can be accessed using list slice.

List Slices
Slice operator works on list also. We know that a slice of a list is its sub-list. For creating
a list slice, we use

[n:m] operator.

>>>print L5 [0]

>>>print L5 [2]

[6, 7, 8]

as the 3rd element of this list is a list. To access a value from this sub-list, we will use

>>>print L5 [2] [0]

>>>print L5 [2] [2]

This will return the part of the list from nth element to mth element, including the first
element but excluding the last element. So the resultant list will have m-n elements in it.

>>> L1 [1:2]

will give

[2]

198
Slices are treated as boundaries, and the result will contain all the elements between
boundaries.

Its Syntax is:

seq = L [start: stop: step]

Where start, stop & step- all three are optional. If you omit first index, slice starts from
„0‟ and omitting of stop will take it to end. Default value of step is 1.

Example

For list L2 containing [“Delhi”, “Chennai”, “Mumbai”]

>>>L2 [0:2]

[“Delhi”, “Chennai”]

Example

>>>list = [10, 20, 30, 40, 50, 60]

>>> list [::2] # produce a list with every alternate element

[10, 30, 50]

>>>list [4:] # will produce a list containing all the elements from 5th position
till end

[50, 60]

Example

>>>list [:3]

[10, 20, 30]

>>>list [:]

[10, 20, 30, 40, 50, 60]

Example

>>> list [-1] # „-1‟ refers to last elements of list

60

will produce a list with every other element

199

You might also like