[go: up one dir, main page]

0% found this document useful (0 votes)
13 views12 pages

Listrr

The document provides an overview of lists and tuples in Python, detailing their characteristics, operations, and functions. It explains list indexing, operations such as concatenation and slicing, and various list functions like append, extend, and sort. Additionally, it introduces tuples, highlighting their immutability and the functions applicable to them.

Uploaded by

divyanshuyt1k
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)
13 views12 pages

Listrr

The document provides an overview of lists and tuples in Python, detailing their characteristics, operations, and functions. It explains list indexing, operations such as concatenation and slicing, and various list functions like append, extend, and sort. Additionally, it introduces tuples, highlighting their immutability and the functions applicable to them.

Uploaded by

divyanshuyt1k
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/ 12

LIST

INTRODUCTION
 Lists are used to store multiple items in a single variable.
 Lists are enclosed in square brackets and the elements of the list are separated by
commas.
 List is a mutable data type, means that the contents of the list can be changed after it
is created.

ex: - L = [12, 23, ‘A’, “45”]


L1 = [ ] # L1 is a blank list
L2 = list( ) # list( ) function is used to create list L2
L3 = [1,2,3,4,5] # L3 is an integer list
L4 = ["ABC", 15, False, 25.5, "male"] # L4 is a list with mix data types
L5 = [‘a’, [2,4,’b’], 56] # L5 is a nested list
INDEXING IN LIST
It is a process in which each element of a list has its index or can be accessed using its index. The
first element of the list has index 0, the next has index 1, and so on. The index of the last
element will be the length of the minus one (Forward indexing).

There is another way (Backward indexing) for indexing from last element (index = -1) to
first element (index = -length of the list).

LIST OPERATIONS
Concatenation (+ Operator): Python allows us to join two or more lists using + operator.
ex: - >>> l1 = [1,3,5,7,9]
>>> l2 = [2,4,6,8,10]
>>> l3 = [‘abc’, “qwe”]
>>>l1 + l2 + l3 # + operator
[1,3,5,7,9,2,4,6,8,10, ‘abc’, “qwe”]
Repetition/ Replication Operator (* operator): Python allows us to replicate a list using
repetition operator depicted by symbol ‘*’.
ex: - >>> str1 = ['Help']
>>> str1 * 4
[' Help ', ' Help ', ' Help’, ' Help']

(3) Membership (IN/ NOT IN operator) :

Like strings, the membership operators IN NOT IN operator returns True if the element is
checks, if the element is present in the list then not present in the list, else it
returns True, returns False.
else returns False. ex: - >>>‘N’ not in [‘A’, ‘P’, ‘S’ ]
ex: - >>>‘N’ in [‘A’, ‘P’, ‘S’ ] True
False >>>‘A’ not in [‘A’, ‘P’, ‘S’ ]
>>>‘S’ in [‘A’, ‘P’, ‘S’ ] False
True

List Slicing: - Like strings, the slicing operation can also be applied to lists. List elements
can be accessed in subparts.
Syntax- list_name[start:stop:step]
L = [2,7,9,10,13,15,17,19,23,25] Slice Generates
L[4: ] [13, 15, 17, 19, 23, 25]
L[ : 3] [2,7,9]
L[2: 5] [9,10, 13]
L[4: : 2] [13, 17, 23]
L[2 : 7 : 2] [9, 13, 17]
L[ : : -1] [25, 23, 19, 17, 15, 13, 10, 9, 7, 2]
L[ : : -2] [25, 19, 15, 10, 7]
L[6 : 1: -2] [17, 13, 9]
L[-8 : 8 ] [9, 10, 13, 15, 17, 19]
L[3 : -2 : 2] [10, 15, 19]
L[6 : -9 : -2] [17, 13, 9]

Traversing: - Traversing means iterating through the elements of a list, one element at a
time.
ex: - >>>L1 = [1,2,3,4] output- 1
>>>for a in L1: 2
print(a) 3
4

Modifying a List element/Mutability of a List: - The elements of a list can be modified by


using L[index]=new_value. Since a list can be modified in place.

ex: - >>>L = [1,2,3,4,5]


>>>L[2] = 11
>>>L[-1] = 22
>>>print (L) #[1,2,11,4,22]

List Comparisons: - The relational operators >, >=, <, <=, ==, != can be applied for
comparison between two lists results will come in True or False. The following rules are
observed:
(a) For equality (==) operator: - Equality evaluates to True only when all the elements of
one list match all the elements of the other list and both the list have the same number of
elements.
(b) For all other operators - The elements are compared sequentially using the operator
under consideration.
(c) If two lists are of different lengths and if one of the list has an element at an index
position and the other list does not have an element at that position then the evaluation
proceeds as follows:

ex: - >>>print( [1,2,3] == [1,2,3]) >>>print( [1,2,8,9] >= [1,9])


True False
>>>print( [1,2,3] != [1,2,3]) >>>print( [1,2] < [1,2,3])
False True
>>>print( [1,2,8,9] < [9,1]) >>>print([2] > [1,2,3])
True True

List Functions
1. len() function
This function returns the length of a list .
len(<list>)
L1 = [13,18,11,16,18,14]
len(L1) will return 6
2. list () function

This function converts the passed argument to a list. The passed argument could be a string, a list or
even a tuple.
list(<argument>)
example s = “Computer”# list(s) # [‘C’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]
tpl=1,2,3,4,5,6 # list(tpl) #(1,2,3,4,5,6]

3. The append () function

The append() function adds an item to the end of the list.


List.append(<item>)
For example,
colours =[“red”,”green”,”blue”]
colours.append(“yellow”)
print(colours)
[“red”,”green”,”blue”,”yellow”]
X=[1,2,3,4,5,6]
x.append(99)
print(x)

4. The extend() function

The extend() method is also used for adding multiple elements (given in the form of a list) to a list.
List.extend(<list>)
That is extend() takes a list as an argument and appends all of the elements of the argument list to
the list object on which extend() is applied.
t1=[‘a’,’b’,’c’]
t2=[‘d’,’e’]
t1.extend(t2)
print(t1) # [‘a’,’b’,’c’,’d’,’e’]
print(t2) # [‘d’,’e’]
5. The insert () function

If you want to insert an element somewhere in between or any position of your choice for such a
requirement insert() is used.
List.insert(<pos>,<item>)
The first argument <pos> is the index of the element before which the second argument <item> to
be added.
t1=[‘a’,’e’,’u’]
t1.insert(2,’i')
print(t1)
[‘a,’e’,’i',’u’]
list.insert(0,x) will insert element x at the front of the list i.e. at index 0.
list.insert(len(list),x) will insert element x at the end of the list i.e. index equal to length of the list
6. The count() function

This function returns the count of the item that you passed as argument. If the given item is not in
the list, it returns zero.
List.count(<item>)
For instance:
L1 = [13,18,20,10,18,23]
print(L1.count(18))
2
print(L1.count(28))
0
7. The Index() function
This function returns the index of first matched item from the list.
List.index(<item>)
L1 = [13,18,11,16,18,14]
print(L1.index(18))
1
However, if the given item is not in the list, it raises exception ValueError.
8. The remove() function

The remove() method removes the first occurrence of given item from the list. It is used as per
following format:
List.remove(<value>)
The remove() will report an error if there is no such item in the list. Consider the example:
t1=[‘a’,’e’,’i',’p’,’q’,’a’,’q’,’p’]
t1.remove(‘a’)
print(t1)
[’e’,’i',’p’,’q’,’a’,’q’,’p’]
t1.remove(‘p’)
print(t1)

[’e’,’i',’q’,’a’,’q’,’p’]
print(t1.remove(‘k’))

ValueError

9. The pop() method

The pop() is used to remove the item from the list. It is used as per the following syntax:

List.pop(<index>)

Thus, pop() removes an element from the given position in the list, and return it. If no index is
specified, pop() removes and returns the last item in the list.

t1 = [‘k’,’a’,’i',’p’,’q’,’u’]

ele = t1.pop(0)

print(ele)

‘k’

10. The reverse() function

The reverse() reverses the item of the list. This is done “in place” i.e. id does not create a new list.
The syntax to use reverse method is:

List.reverse()

For example:

t1 = [‘e’,’i',’q’,’a’,’q’,’p’]

t1.reverse()

print(t1)

[‘p’,’q’,’a’,’q’,’i',’e’]

11. The sort() function

The sort() function sorts the items of the list, by default in increasing order. This is done “in place”
i.e. it does not create a new list. It is used as per following syntax:

List.sort()

For example:

t1 = [‘e’,’i',’q’,’a’,’q’,’p’]

t1.sort()

print(t1)

[‘a’,’e’,’i',’p’,’q’,’q’]

To sort a lit in decreasing order using sort(), you can write:

List.sort(reverse=True)

12. min() function


This function returns the minimum value present in the list. This function will work only if all
elements of the list are numbers or strings. This function gives the minimum value from a given list.
Strings are compared using its ordinal values/Unicode values. This function is used as per following
format:

min(<list>)

For example L1 = [13,18,11,16,18,14] and L2 = [‘a’, ‘e’ ‘i', ‘o’ ,’U’] then

min(L1) will return 11 and min(L2) will return ‘U’

13. max() function

This function returns the maximum value present in the list. This function will work only if all
elements of the list are numbers or strings. This function gives the maximum value from a given list.
Strings are compared using its ordinal values/Unicode values. This function is used as per following
format:

max(<list>)

For example L1 = [13,18,11,16,18,14] and L2 = [‘a’, ‘e’ ‘i', ‘o’ ,’U’] then

max(L1) will return 18 and max(L2) will return ‘o’

14. sum() function

This function returns the total of values present in the list. This function will work only if all elements
of the list are numbers. This function gives the total of all values from a given list. This function is
used as per following format:

sum(<list>)

For example L1=[13,18,11,16,18,14] then sum(L1) will return 90

15. The clear() function

This method removes all the items from the list and the list becomes empty list after this function.
This function returns nothing. It is used as per following format:

List.clear()

For instance:

L1=[2,3,4,5]

L1.clear()

print(L1)

[]
Assignment- LIST
Q1. Write a program to print list having numbers less than 20.
Q.2 What will be the output of the following program?
l=[6,12,18,24,30]
for i in l:
for j in range(1,i%4):
print(j,'#',end='')
print( )
Q.3 Write a program that reverses a list of integers.
Q.4 Write a program to find the number of times an element occurs in the list.
Q.5 Write a program to find the largest and smallest number in a list.
Q.6 Write a program to check if a number is present in the list or not. If the number is
present, print the position of the number. Print an appropriate message if the number
is not present in the list.
TUPLE
 A tuple is a collection which is ordered and immutable.
 Elements of a tuple are enclosed in parenthesis and are separated by commas.
 Tuples can store a sequence of values belonging to any type.
Ex:- T1 = ( ) # Empty Tuple
T2 = (4,5,6) # Tuple of integers
T3 = (1.5,4,9) # Tuple of numbers
T4 = (‘x’, ‘y’, ‘z’) # Tuple of characters
T5 = (‘a’,1.5,’APS’,45) # Tuple of mixed values
T6 = (‘KVS’, ‘LBS’, ‘APSSP’) # Tuple of strings
>>>t2 = (10,) # Single element tuple
Note:- comma is necessary in single value tuples. Without a comma it will be a value, not a
tuple.
>>>t3=(10,20,30,40,50) # Long tuple
>>>t4=(6,(4,5),9,7) # Nested Tuple
●tuple( ) function is used to create a tuple from other sequences.
●Indexing of tuple is similar to indexing of list.
●Difference between List and Tuple

TRAVERSING A TUPLE

Ex:-
T1=(2,4,6,8,10) Output:
for a in T1:
print(a)

Unpacking Tuples
Creating a tuple from a set of values is called packing.
Creating individual values from a tuple’s element is called unpacking.

For example
t = (1, 2, ‘A’, ‘B’) # Packing

The length of above tuple t is 4 as there are four elements in it.


w,x,y,z = t # Unpacking

Tuple functions

1. The len() funtion

For example:
emp = (‘John’, 10000, 24, ‘Sales’)
print(len(emp))
4

2. The max() function

This method returns the element from the tuple having maximum value.

Example:
tp1 = (10,12,14,20,22,24,30,32,34,-2)
print(max(tp1))
34
tp2 = (“Karan”, “Zubin”, “Zara”, “Ana”)
print(max(tp2))
Zubin

Note that max() applied on sequences like tuples/lists etc. will return a maximum value
ONLY IF the sequence contains values of same type.

3. The min() function

Example:
tp1 = (10,12,14,20,22,24,30,32,34,-2)
print(min(tp1))
-2
tp2 =(“Karan”, “Zubin”, “Zara”, “Ana”)
print(min(tp2))
Ana

4. The index() function

The index() works with tuples in the same way it works with lists.

Example:
t1 =(3,4,5,6.0)
print(t1.index(5))
2

5. The count() function


The count() method returns the count of a member element/object in a given sequence
(list/tuple).

Example:
t1=(2,4,2,5,7,4,8,9,9,11,7,2)
print(t1.count(2))
3
t1.count(7)
2
For an element not in tuple, it returns 0.

6. The tuple() function

This method is actually constructor method that can be used to create tuples from
different types of values.

Example:
a. Creating empty tuple
>>>tuple()
()

b. Creating a tuple from a string


t = tuple(“abc”)
print(t)
(‘a’,’b’,’c’)

c. Creating a tuple from a list


t = tuple([1,2,3])
print(t)
(1,2,3)

d. Creating a tuple from keys of a dictionary


t1 = tuple({1:”1”, 2:”2”})
print(t1)
(1,2)

7. The sorted() function


This function is used to take a tuple as argument and converts this tuple to a sorted list.
It has another argument called reverse. If reverse is set to True then tuple is sorted in
descending order otherwise tuple will be sorted in ascending order.

t1 =(3,4,5,6,0)
print(sorted(t1))
[0, 3, 4, 5, 6]
print(sorted(t1, reverse = True))
[6, 5, 4, 3, 0]
Indirectly Modifying Tuples
Tuple is Immutable:
Tuple is an immutable data type. It means that the elements of a tuple cannot be
changed after it has been created.
>>> tuple1 = (1,2,3,4,5)
>>> tuple1[4] = 10
TypeError: 'tuple' object does not support item assignment

Tuple operations:
Concatenation:-
Python allows us to join tuples using concatenation operator depicted by symbol +.

>>> tuple1 = (1,3,5,7,9)


>>> tuple2 = (2,4,6,8,10)
>>> tuple1 + tuple2 #concatenates two tuples
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
Repetition :-
Repetition operation is depicted by the symbol *. It is used to repeat elements of a tuple.
>>> tuple1 = ('Hello','World')
>>> tuple1 * 3
('Hello', 'World', 'Hello', 'World', 'Hello', 'World')

Membership The ‘in’ operator checks the presence of element in


tuple. If the element is present it returns
True, else it returns False.

>>>h1 = (‘H’ , ‘M’)


>>>’H’ in h1
True
>>>’m’ not in h1

S Like string and list, slicing can be applied to tuples also.


l
i >>>t1 = (1, 2, 3, 7, 8, 9)
c >>>t1[2:4]
i (3, 7)
n >>>t1 =(10, 20, 30, 40, 50,
g 60, 70, 80)
>>>t1[2 : 7]
(30, 40, 50, 60, 70)
>>>t1[ : 5]
(10, 20, 30, 40, 50)
>>>t1[: : -1]
(80, 70, 60, 50, 40, 30, 20, 10)
Assignment Tuple

What will be stored in Ans.


variables a, b, c, d, e, f, g, h after ()
following statements? perc = (80, 88, 83, 86)
(88, 85, 80, 88, 83, 86) (88, 85)
a = perc[2:2] (88, 85, 80, 88)
b = perc[2:] 83
c = perc[:2] (80, 88)
d = perc[:-2] ()
e = perc[-2] (88, 85, 80, 88, 83, 86)
f = perc[2:-2]
g = perc[-2:2]
h = perc[:]

Q. Write a program to create a tuple and find sum of its alternate elements?

Q Write a program to input n numbers from the user. Store these numbers in a tuple. Print the
maximum and minimum number from this tuple.

Q. Write a program to count vowels in a tuple?

You might also like