Python
Python
LIST
A list is a sequence
Like a string, a list is a sequence of values.
In a string, the values are characters;
In a list, they can be any type. The values in list are called elements or sometimes
items.
There are several ways to create a new list; the simplest is to enclose the elements
in square brackets ([ and ]):
>>> print(cheeses[0])
Cheddar
Unlike strings, lists are mutable because you can change
the order of items in a list or reassign an item in a list.
When the bracket operator appears on the left side of an
assignment, it identifies the element of the list that will be
assigned.
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print(numbers)
[17, 5]
List can be viewed as relationship between indices and
elements.
This relationship is called a mapping; each index “maps
to” one of the elements.
List indices work the same way as string indices:
• Any integer expression can be used as an index.
• If you try to read or write an element that does not exist,
you get an IndexError.
• If an index has a negative value, it counts backward from
the end of the list.
The in operator also works on lists.
>>> animals = [‘cow', ‘lion', ‘elephant']
>>> ‘lion' in animals
True
>>> ‘book' in animals
False
TRAVERSING A LIST
The most common way to traverse the elements of
a list is with a for loop.
The syntax is the same as for strings:
for word in animals:
print(word)
If you want to write or update the elements, you need the indices. A common way
to do that is to combine the functions range and len:
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
A for loop over an empty list never executes the body:
for x in empty:
print('This never happens.')
Although a list can contain another list, the nested list still counts as a
single element. The length of this list is four:
['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
EXAMPLE 1.PY
Write a Python program to sum all the items in a list.
LI1.PY
def sum_list(items):
sum_numbers = 0
for x in items:
sum_numbers += x
return sum_numbers
print(sum_list([1,2,-8]))
EXAMPLE LI2.PY
Write a Python program to multiply all the
items in a list.
LI2.PY
def multiply_list(items):
tot = 1
for x in items:
tot *= x
return tot
print(multiply_list([1,2,-8]))
EXAMPLE LI3.PY
Write a Python program to get the largest number from a list.
LI3.PY
def max_num_in_list( list ):
max = list[0]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))
EXAMPLE 4.PY
Write a Python program to get the smallest number
from a list.
LI4.PY
def smallest_num_in_list( list ):
min = list[ 0 ]
for a in list:
if a < min:
min = a
return min
print(smallest_num_in_list([1, 2, -8, 0]))
EXAMPLE LI5.PY
Write a Python program to count the number of strings
where the string length is 2 or more and the first and last
character are same from a given list of strings.
numlist = list()
while (True):
value = float(inp)
numlist.append(value)
print('Average:', average)
LISTS AND STRINGS
A string is a sequence of characters and a list is a sequence of values, but
a list of characters is not the same as a string.
To convert from a string to a list of characters, you can use list:
>>> s = 'spam'
>>> t = list(s)
>>> print(t)
['s', 'p', 'a', 'm']
The list function breaks a string into individual letters.
If you want to break a string into words, you can use the
split method:
>>> s = 'pining for the fjords'
>>> t = s.split()
>>> print(t)
['pining', 'for', 'the', 'fjords']
>>> print(t[2])
the
You can call split with an optional argument called a delimiter
>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> s.split(delimiter)
['spam', 'spam', 'spam']
join is the inverse of split. It takes a list of strings and
concatenates the elements.
join is a string method, so you have to invoke it on the delimiter
and pass the list as a parameter:
What if we wanted to print out the day of the week from those lines that start with
“From”?
The split method is very effective when faced with this kind of problem.
We can write a small program that looks for lines where the line starts with “From”,
split those lines, and then print out the third word in the line:
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if not line.startswith('From '): continue
words = line.split()
print(words[2])
The program produces the following output:
Sat
Fri
Fri
Fri
OBJECTS AND VALUES
If we execute these assignment statements:
a = 'banana'
b = 'banana‘
we know that a and b both refer to a string, but we don’t know
whether they refer to the same string. There are two possible states:
In one case, a and b refer to two different objects that have the same value.
In the second case, they refer to the same object.
To check whether two variables refer to the same object, you can use the
is operator.
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
In this example, Python only created one string object, and both a and b
refer to it.
But when you create two lists, you get two objects:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
In this case we would say that the two lists are equivalent,
because they have the same elements, but not identical, because
they are not the same object.
If two objects are identical, they are also equivalent, but if they
are equivalent, they are not necessarily identical.
ALIASING
If a refers to an object and you assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
The association of a variable with an object is called a reference. In this example, there are two
references to the same object.
An object with more than one reference has more than one name, so we say that the object is
aliased.
If the aliased object is mutable, changes made with one alias affect the other:
>>> b[0] = 17
>>> print(a)
[17, 2, 3]
LIST ARGUMENTS
When you pass a list to a function, the function gets a reference to the list.
If the function modifies a list parameter, the caller sees the change.
For example, delete_head removes the first element from a list:
def delete_head(t):
del t[0]
Here’s how it is used:
>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print(letters)
['b', 'c']
The parameter t and the variable letters are aliases for the same object.
It is important to distinguish between operations that modify lists and operations that create
new lists. For example, the append method modifies a list, but the + operator creates a new list:
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print(t1)
[1, 2, 3]
>>> print(t2)
None
>>> t3 = t1 + [3]
>>> print(t3)
[1, 2, 3]
>>> t2 is t3
False
EXAMPLE 8.PY
Write a Python program to print a specified list after removing the
specified element.
Sample List :
['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
Enter Item to delete: Black
Expected Output :
['Red', 'Green', 'White', 'Pink', 'Yellow']
LI8.PY
def cdelete(clist,item):
clist.remove(item)
clist=['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
print('Before deleting:',clist)
item=input("Enter the Item to remove:")
if item in clist:
cdelete(clist,item)
print('After calling delete:',clist)
print(clist)
else:
print("Item is not in the list")
EXAMPLE 9.PY
Write a Python program to get a list of words and convert it into a string using
required delimeter.
Example: Two roads diverged in the woods, I take the one less
travelled.
Replace: take->took
Output: Two roads diverged in the woods, I took the one less
travelled.
LI11.PY
sentence="Two roads diverged in the woods, I take the one less travelled."
print(sentence)
sentence=sentence.split()
for i,x in enumerate(sentence):
if x==old_word:
sentence[i]=new_word
sentence=" ".join(sentence)
print(sentence)
STRINGS
A string is a sequence of characters. You can access the
characters one at a time with the bracket operator:
>>> fruit = 'banana'
>>> letter = fruit[1]
The second statement extracts the character at index
position 1 from the fruit variable and assigns it to the letter
variable.
The expression in brackets is called an index. The index
indicates which character in the sequence you want (hence
the name).
>>> print(letter)
a
For most people, the first letter of “banana” is b, not a. But in Python, the index is
an offset from the beginning of the string, and the offset of the first letter is zero.
>>> letter = fruit[0]
>>> print(letter)
b
So b is the 0th letter (“zero-eth”) of “banana”, a is the 1th letter (“one-eth”), and
n is the 2th letter.
You can use any expression, including variables and operators, as an index, but
the value of the index has to be an integer. Otherwise you get:
>>> letter = fruit[1.5]
TypeError: string indices must be integers
GETTING THE LENGTH OF A
STRING WITHOUT USING FUNCTION
The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on.
EXAMPLE 2.PY
Write a Python program to count the character frequency in a
string.
def char_frequency(str1):
dict = {}
for n in str1:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
return dict
print(char_frequency(input("Enter the String"))
EXAMPLE 3.PY
Write a Python program to get a string made of the first 2 and the
last 2 chars from a given a string. If the string length is less than
2, return empty string.
3.PY
def string_both_ends(str):
if len(str) < 2:
return ‘ '
start at the beginning, select each character in turn, do something to it, and continue
until the end. This pattern of processing is called a traversal.
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
EXAMPLE: 4.PY
Write a while loop that starts at the first character in the string and
works its way forward to the last character in the string, printing each
letter on a separate line
4.PY
def disp(str):
index = 0
while index < len(str):
letter = str[index]
print(letter)
index = index + 1
Write a while loop that starts at the last character in the string and works its way
backwards to the first character in the string, printing each letter on a separate
line
5.PY
def disp(str):
index = len(str)-1
while index >= 0:
letter = str[index]
print(letter)
index = index - 1
of its first char have been changed to '$', except the first char itself.
return str1
character:
>>> print(s[0:5])
Monty
>>> print(s[6:12])
Python
The [n : m] operator returns the part of the string from the “n-th” character to the “m-th”
If you omit the first index (before the colon), the slice starts at the beginning of the string.
If you omit the second index, the slice goes to the end of the string:
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'
If the first index is greater than or equal to the second the result is an empty
>>> fruit[3:3]
‘'
An empty string contains no characters and has length 0, but other than that, it
>>> fruit[:]
‘banana’
EXAMPLE 7.PY
Write a Python program to get a single string from two given strings,
separated by a space and swap the first two characters of each string.
Sample String1 : 'abc‘
This example concatenates a new first letter onto a slice of greeting. It has no
effect on the original string.
EXAMPLE: 8.PY
Write a Python program to add 'ing' at the end of a given string (length should be at
least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string
length of the given string is less than 3, leave it unchanged.
if length > 2:
if str1[-3:] == 'ing':
str1 += 'ly'
else:
str1 += 'ing'
return str1
str=input("Enter the string:") #input abc, string
str=add_string(str)
print(str)
EXAMPLE: 9.PY
Write a Python program to find the first appearance of the substring 'not' and 'poor'
from a given string, if ‘not' follows the 'poor', replace the whole 'not'...'poor'
substring with 'good'. Return the resulting string.
Input Tag:b
Input Word: Python Tutorial
<b>Python Tutorial </b>
def add_tags(tag, word):
return "<%s>%s</%s>" % (tag, word, tag)
tag=input("Enter the tag:")
str=input("Enter the string:")
html=add_tags(tag,str)
print("HTML OUTPUT:",html)