You are on page 1of 9

RAGHU ENGINEERING COLLEGE (A)

Department of CSE
CRT
Python Programming
Week-2
Topics:

 Strings and its functions


 Lists
o Properties
o Methods
o List copying
o List comprehension
 Tuples
o Properties
o Methods
o zip() function

Strings:
• Python strings are immutable. In simple words, a mutable object can be changed after
it is created, and an immutable object cannot be changed.
• Consider the following code:
s="abcdef"
s[2]='d'
print(s)
• For this code, we will get an error saying:
“ 'str' object does not support item assignment “, so s cannot be modified.
• Two strings can be concatenate with ‘+’, but it can’t be used with number and ‘*’ can
be used with number on strings.
String functions:

 isalpha()
 isdigit()
 upper()
 lower()
 swapcase()
 islower()
 isupper()
 capitalize()
 count(substring, start=..., end=...)
 endswith(suffix)
 find(sub)
 index(sub[, start[, end]] )
 isalnum()
 isdecimal()
 istitle()
 separator.join(iterable)
 lstrip()
 rstrip()
 strip()
 replace(old, new [, count])
 rfind(sub[, start[, end]] )
 rindex(sub[, start[, end]] )
 split([separator])
 startswith(prefix[, start[, end]])
 title()
 len(s)
List Methods:

 split()
 map()
 insert(index,element)
 pop(index)
 append(element)
 count(element)
 index(element)
 remove(element)
 reverse()
 sort()
 extend(list)
 len(list)
 min(list)
 max(list)
 list(seq)
 sum(list)
Nested Lists: Nested list is a list within another list.

List Comprehension:
• Python also supports computed lists called list comprehensions having the following
syntax.

• List = [expression for variable in sequence]

• Where, the expression is evaluated once, for every item in the sequence.
• This is mainly beneficial to make new lists where each element is obtained by
applying some operations to each member of another sequence or iterable.

• pairs = [ (x,y) for x in range(4) for y in range(3) if (x+y)%3 == 0 ]


• data = [x for x in range(5)]
temp = [x for x in range(7) if x in data and x%2==0]
print(temp)

sorted() vs sort():
• The sorted() method sorts the elements of a given iterable in a specific order -
Ascending or Descending.

• A list also has sort() method which performs the same way as sorted().
• Only difference being, sort() method doesn't return any value and changes the original
list itself where as sorted() method only returns sorted list but it does not change the
original list.

Tuple:
• Like lists, tuple is another data structure supported by Python. It is very similar to lists
but differs in two things.

• First, a tuple is a sequence of immutable objects.


• This means that while you can change the value of one or more items in a list, you
cannot change the values in a tuple.

• Second, tuples use parentheses to define its elements whereas lists use square
brackets.

• Creating a tuple is very simple and almost similar to creating a list.

• For creating a tuple, generally we need to just put the different comma-separated
values within a parentheses as shown below:
t = (val1, val2,….. )
Example: t=(10,20,30,40,50)

• t[2]=55 is not possible because tuple is mutable.


• Like other sequences (strings and lists) covered so far, indices in a tuple also starts at
0.

• We can even perform operations like slice, concatenate, etc. on a tuple


• For example, to access values in tuple, slice operation is used along with the index or
indices to obtain value stored at that index

Tuple Operations:

 len(tuple)
 Concatenation
 Repition
 Membership
 Comparison
o <
o >
o ==
 max(tuple)
 min(tuple)
 tuple(iterable)
 index(element)
 count(tuple)

zip() function:
• The zip() is a built-in function that takes two or more sequences and "zips" them into
a list of tuples.

• The tuple thus, formed has one element from each sequence.
• The * operator can be used in conjunction with zip() to unzip the list.
zip(*zippedList)

Unzipping:
The * operator can be used in conjunction with zip() to unzip the list.

Program:
coordinate = ['x', 'y', 'z']
value = [3, 4, 5]
result = zip(coordinate, value)
resultList = list(result)
print(resultList)
c, v = zip(*resultList)
print('c =', c)
print('v =', v)

Sample Output:
[('x', 3), ('y', 4), ('z', 5)]
c = ('x', 'y', 'z')
v = (3, 4, 5)

MCQs
testmoz.com/8731154 - Lists
testmoz.com/8747232 – Tuples & Strings

Programs
1. sub string in reverse(strings)
Write a program to extract a substring from last but nth character to first character of the
given string
Input Format
Consists of 2 inputs from user: 1. String 2. Integer value n
Constraints
You can assume n value is never greater than (length of string-1)
Output Format
display the extracted sub string
Sample Input 0
abcdefghi
3
Sample Output 0
fedcba
Sample Input 1
12345678
7
Sample Output 1
1
Sample Input 2
computer
0
Sample Output 2
retupmoc

2. Last character in ASCII(strings)


Write a program that reads a string and finds the character from the string which occurs last
in ASCII table.
Input Format
String entered by user
Constraints
.
Output Format
display the character from the string which occurs last in ASCII table.
Sample Input 0
AB@\CD
Sample Output 0
\
Sample Input 1
pYtThon
Sample Output 1
t

3. Unique Characters(strings)
Write a program that removes all the douplicate characters from a given string
Input Format
String entered by user
Constraints
.
Output Format
Display string after deleting all the douplicate characters from a given string
Sample Input 0
hello
Sample Output 0
helo
Sample Input 1
abbbbbbcdef
Sample Output 1
abcdef

4. Numeric Sum(strings)
 Consider the numeric value of a is 1, b is 2, c is 3,.... z is 26.
 Then Numeric value of word "raghu" is r(18)+a(1)+g(7)+h(8)+u(21) = 55
 Similarly numeric value of "college" is 3+15+12+12+5+7+5 = 59
Find the numeric sum of characters at odd places if the given string is of odd length
Find the numeric sum of characters at even places if the given string is of even length
Input Format
string entered by user
Constraints
Assume all the characters in the string are lower case alphabets
Output Format
Display Numeric sum
Sample Input 0
raghu
Sample Output 0
46
Sample Input 1
abcd
Sample Output 1
6
5. Insert element at a given position(lists)
write a program to insert element at a given position in a list (lists)
Input Format
first line contains number as input
second line contains position as input
Constraints
.
Output Format
list as output
Sample Input 0
10 20 30 40 50
80
3
Sample Output 0
[10, 20, 30, 80, 40, 50]

6. Finding cubes (Lists)


Kavisha has a set of items where she wants to find the cube of items within a specified range
Input Format
List of numbers separated by spaces as input
Range as an input
Constraints
List should not be empty
Range < length of the List
Output Format
List as an output
(or)
Invalid Range
Sample Input 0
3247958
3
Sample Output 0
[27, 8, 64, 7, 9, 5, 8]
Sample Input 1
5234
6
Sample Output 1
Invalid Range

7. Sum of individual digit operation on List elements (Lists)


Crete new list by finding Sum of individual digit operation on each element of a list (Lists)
Input Format
List as input
Constraints
List elements should be positive
Output Format
List as output
Sample Input 0
10 232 45
Sample Output 0
[1, 7, 9]

8. Update the value at given position in list(lists)


To update the value at given position in list and display updated list
if given position exceeds the length of list then display "element not found for updation"
Input Format
first line contains list of numbers as input separated by spaces
second line contains the element to be updated as the input
third line contains position as the input
Constraints
.
Output Format
list as output
Sample Input 0
10 2 25 7 86
20
3
Sample Output 0
[10, 2, 25, 20, 86]
Sample Input 1
22 77 6 88 9
56
5
Sample Output 1
element not found for updation

9. Generate unique sublists after splitting the items in list(lists)


To generate unique sublists after splitting the items in list
Input Format
list of strings separated by spaces as input
Constraints
.
Output Format
unqiue sublists as output
Sample Input 0
abc bcd def
Sample Output 0
[['a'], ['b'], ['c'], ['d'], ['e'], ['f']]
Sample Input 1
hai cse ece
Sample Output 1
[['h'], ['a'], ['i'], ['c'], ['s'], ['e']]

10. To count number of strings whose string length is two or more and the first and
last character are same from the given list (Lists)
To count number of strings whose string length is two or more and the first and last character
are same from the given list (Lists)
Input Format
List of strings separated by spaces as input
Constraints
String length >= 2
Output Format
Count of strings which satisfy the requirement
Sample Input 0
abc aba abb ccc
Sample Output 0
2

You might also like