0% found this document useful (0 votes)
15 views

Python 6 (List and Tuples)

Uploaded by

tolin78730
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Python 6 (List and Tuples)

Uploaded by

tolin78730
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

LIST & TUPLES

LIST
 A list can be defined as a collection of values or items of different
types. The items in the list are separated with the comma (,) and
enclosed with the square brackets [].
 Characteristics of Lists
 The lists are ordered.
 The element of the list can be accessed by index.
 The lists are mutable types.
How to Create and Assign Lists
A list can be define as below
 L1 = ["John", 102, "USA"]
 L2 = [1, 2, 3, 4, 5, 6]
LIST
How to Access Values in Lists
 Slicing works similar to strings; use the square bracket slice
operator ( [ ] ) along with the index or indices.
LIST
 We can get the sub-list of the list using the following syntax.
 list_varible(start:stop:step)
e.g. list = [1,2,3,4,5,6,7]
 list[1:6:2]
 Output: [2, 4, 6]
 Unlike other languages, Python provides the flexibility to use the
negative indexing also. The negative indices are counted from
the right. The last element (rightmost) of the list has the index -1
LIST
 list = [1,2,3,4,5]
 print(list[-1]) // 5
 print(list[-3:]) // [3, 4, 5]
 print(list[:-1]) // [1, 2, 3, 4]
 print(list[-3:-1]) // [3, 4]
Updating List values
 Lists are the most versatile data structures in Python since they are mutable,
and their values can be updated by using the slice and assignment operator.
 list = [1, 2, 3, 4, 5, 6]
 list[2] = 10
 print(list) // [1, 2, 10, 4, 5, 6]
 # Adding multiple-element
 list[1:3] = [89, 78]
 print(list) // [1, 89, 78, 4, 5, 6]
LIST
How to Remove List Elements and Lists
 To remove a list element, you can use either the del statement if you know exactly
which element(s) you are deleting or the remove() method if you do not know.
 list=[1,'abc',6,7,8]
 >>> del list[2]
 >>> list // [1, 'abc', 7, 8]
 >>> list.remove('abc')
 >>> list // [1, 7, 8]
 To remove an entire list, use the del statement:
 del List
 Pop()
 List.pop()
 Removes an element from a list.
 This method differs from .remove() in two ways:
 You specify the index of the item to remove, rather than the object itself.
 The method returns a value: the item that was removed.
Python List Operator

Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8] to perform ope


ration.
OPERATOR DESCRIPTOR EXAMPLE
Repetition The repetition operator enables the list L1*2 = [1, 2, 3, 4, 1, 2, 3, 4]
elements to be repeated multiple times.
Concatenation It concatenates the list mentioned on l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8]
either side of the operator.
Membership It returns true if a particular item exists in print(2 in l1) prints True.
a particular list otherwise false.
Iteration The for loop is used to iterate over the list for i in l1: print(i)Output1 2 3
elements. 4
Built in functions
 len(list): It is used to calculate the length of the list.
L1 = [1,2,3,4,5,6,7,8]
print(len(L1)) // 8
 max(list): It returns the maximum element of the list
L1 = [12,34,26,48,72]
print(max(L1)) //72
 min(list): It returns the minimum element of the list.
L1 = [12,34,26,48,72]
print(min(L1)) //12
Built in functions
 sorted()
 sorted() method sorts the given sequence either in ascending order or in descending order and
always return the a sorted list. This method doesnot effect the original sequence.

list= [3,5,1,7,9,4,23]
Print(Sorted(list)) // [1, 3, 4, 5, 7, 9, 23]
Print(Sorted(list),reverse = True) // [23,9,7,5,4,3,1]
 Sort()
 sort() function is very similar to sorted() but unlike sorted it returns nothing and makes changes
to the original sequence. Moreover, sort() is a method of list class and can only be used with
lists.
Syntax: List_name.sort(key, reverse=False)
 reverse: reverse=True will sort the list descending. Default is reverse=False
 key: A function to specify the sorting criteria(s)
 def myFunc(e):
 return len(e)

 x = ['CSE', 'Pyhton', 'DBMS', 'SE']

 x.sort(key=myFunc)
 print(x)
Built in functions
Reversed():
 for t in reversed(list):
print(t) // 23, 9,7,5,4,3,1

Reverse():
list.reverse()
list // [10, 9, 5, 4, 7, 2]
 reverse() actually reverses the elements in the container. reversed()
doesn't actually reverse anything, it merely returns an object that can be
used to iterate over the container's elements in reverse order. If that's what
you need, it's often faster than actually reversing the elements.
 Append:
list= [2,7,4,5,9]
list.append(10)
list // [2, 7, 4, 5, 9, 10]
Built in functions

 insert() is an inbuilt function in Python that inserts a given


element at a given index in a list.
Syntax :
 list_name.insert(index, element)
 The index() method returns the index of the specified element in
the list.
syntax :
 list.index(element, start, end)
 element - the element to be searched
 start (optional) - start searching from this index
 end (optional) - search the element up to this index
TUPLES
 Python Tuple is used to store the sequence of immutable Python objects. The
tuple is similar to lists since the value of the items stored in the list can be
changed, whereas the tuple is immutable, and the value of the items stored in
the tuple cannot be changed.
Creating a tuple
 A tuple can be written as the collection of comma-separated (,) values
enclosed with the small () brackets. The parentheses are optional but it is
good practice to use. A tuple can be defined as follows.
 T1 = (101, "Peter", 22)
 T2 = ("Apple", "Banana", "Orange")
 T3 = 10,20,30,40,50
 Creating a tuple with single element is slightly different. We will need to put
comma after the element to declare the tuple.
tup1 = ("JavaTpoint")
print(type(tup1)) // <class 'str'>
#Creating a tuple with single element
tup2 = ("JavaTpoint",)
print(type(tup2)) // <class 'tuple'>
TUPLE
How to Access Values in Tuples
 Slicing works similarly to lists. Use the square bracket slice
operator ( [ ] ) along with the index or indices.
TUPLE
How to Update Tuples
 Like numbers and strings, tuples are immutable, which means you cannot
update them or change values of tuple elements
 Adding Elements in tuple
 #tuples are immutable, so you can not add new elements
 #using merge of tuples with the + operator you can add an element and it
will create a new tuple
 tuplex = (4, 6, 2, 8, 3, 1)
 tuplex = tuplex + (9,)
 print(tuplex) // (4,6,2,8,3,1,9)
 #adding items in a specific index
 tuplex = tuplex[:5] + (15, 20, 25) + tuplex[5:]
 print(tuplex) // (4, 6, 2, 8, 3,15,20,25, 1)

.
TUPLE

 #use other way to add items in list


#converting the tuple to list
listx = list(tuplex)
listx.append(30)
tuplex = tuple(listx)

How to Remove Tuple Elements and Tuples


 Removing individual tuple elements is not possible. There is, of
course, nothing wrong with putting together another tuple with the
undesired elements discarded.
 To explicitly remove an entire tuple, just use the del statement
Tuple assignment
 Python has a very powerful tuple assignment feature that allows a tuple of variables on the
left of an assignment to be assigned values from a tuple on the right of the assignment.
 b = ("Bob", 19, "CS") # tuple packing
 In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the variables/names on
the right:
 >>> b = ("Bob", 19, "CS")
 >>> (name, age, studies) = b # tuple unpacking
 >>> name
 'Bob'
 >>> age 19
 >>> studies 'CS‘
 Once in a while, it is useful to swap the values of two variables.
 Tuple assignment solves this problem neatly:
 (a, b) = (b, a)
 The left side is a tuple of variables; the right side is a tuple of values. Each value is assigned to
its respective variable. All the expressions on the right side are evaluated before any of the
assignments. This feature makes tuple assignment quite versatile.
Basic Tuple operations

Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are


declared

OPERATOR DESCRIPTION EXAMPLES


Repetition The repetition operator enables T1*2 = (1, 2, 3, 4, 5, 1, 2, 3, 4,
the tuple elements to be 5)
repeated multiple times.
Concatenation It concatenates the tuple T1+T2 = (1, 2, 3, 4, 5, 6, 7, 8,
mentioned on either side of the 9)
operator.
Membership It returns true if a particular print (2 in T1) prints True.
item exists in the tuple
otherwise false
Iteration The for loop is used to iterate for i in T1: print(i)Output1 2 3
over the tuple elements. 45
Python Tuple inbuilt functions

S.No. FUNCTION DESCRIPTION


1 len(tuple) It calculates the length
of the tuple.
2 max(tuple) It returns the maximum
element of the tuple
3 min(tuple) It returns the minimum
element of the tuple.
List vs. Tuple
SN List Tuple
1 The literal syntax of list is shown by the []. The literal syntax of the tuple is
shown by the ().
2 The List is mutable. The tuple is immutable.
3 The List has the a variable length. The tuple has the fixed length.
4 The list provides more functionality than a tuple. The tuple provides less
functionality than the list.
5 The list is used in the scenario in which we need to store The tuple is used in the cases
the simple collections with no constraints where the value where we need to store the
of the items can be changed. read-only collections i.e., the
value of the items cannot be
changed. It can be used as the
key inside the dictionary.
6 The lists are less memory efficient than a tuple. The tuples are more memory
efficient because of its
immutability.
Multi-dimensional lists in Python

 There can be more than one additional dimension to lists in Python.


 a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
 print(a)
 Output:[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
 a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
 for record in a:
 print(record)
 OUTPUT:
[2, 4, 6, 8, 10]
[3, 6, 9, 12, 15]
[4, 8, 12, 16, 20]
Multi-dimensional lists in Python

 a = [ [2, 4, 6, 8 ],
 [ 1, 3, 5, 7 ],
 [ 8, 6, 4, 2 ],
 [ 7, 5, 3, 1 ] ]

 for i in range(len(a)) :
 for j in range(len(a[i])) :
 print(a[i][j], end=" ")
 print()
 OUTPUT:
2468
1357
8642
7531
Lists Can Be Nested
 You have seen that an element in a list can be any sort of object.
That includes another list. A list can contain sublists, which in
turn can contain sublists themselves, and so on to arbitrary
depth.
 >>> x = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j']
Lists Can Be Nested

 >>> x[1]
 ['bb', ['ccc', 'ddd'], 'ee', 'ff']
 >>> x[1][0]
 'bb'
 >>> x[1][1]
 ['ccc', 'ddd']
 >>> x[1][2]
 'ee'
 >>> x[1][3]
 'ff‘
 >>> print(x[1][1][0], x[1][1][1])
 ccc ddd
List Comprehension in Python
 List comprehensions are used for creating new lists from other
iterables.
 As list comprehensions return lists, they consist of brackets
containing the expression, which is executed for each element
along with the for loop to iterate over each element.
 This is the basic syntax:
 new_list = [expression for_loop_one_or_more conditions]
For example, find the squares of a number using the for loop
 numbers = [1, 2, 3, 4]
 squares = []
 for n in numbers:
 squares.append(n**2)
 print(squares)
List Comprehension in Python

 Finding squares using list comprehensions:


 numbers = [1, 2, 3, 4]
 squares = [n**2 for n in numbers]
 print(squares)
 Finding Comman Numbers from two Lists
 list_a = [1, 2, 3, 4]
 list_b = [2, 3, 4, 5]
 common_num = []
 for a in list_a:
 for b in list_b:
 if a == b:
 common_num.append(a)
 print(common_num)
List Comprehension in Python

 #Find common numbers from two lists using list comprehension:


 list_a = [1, 2, 3, 4]
 list_b = [2, 3, 4, 5]
 common_num = [a for a in list_a for b in list_b if a == b]
print(common_num)
 # Output: [2, 3, 4]

You might also like