Professional Documents
Culture Documents
IV Unit-New
IV Unit-New
operations-List Methods. Tuples: Creating, Accessing, Updating and Deleting Elements in a tuple –
Nested tuples– Difference between lists and tuples. Dictionaries: Creating, Accessing, Updating
and Deleting Elements in a Dictionary – Dictionary Functions and Methods - Difference between
Lists and Dictionaries.
Python List
Python Lists are the most versatile compound data types. A Python list contains items separated by
commas and enclosed within square brackets ([]). To some extent, Python lists are similar to arrays
in C. One difference between them is that all the items belonging to a Python list can be of different
data type where as C array can store elements related to a particular data type.
The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list
concatenation operator, and the asterisk (*) is the repetition operator. For example
Example
my_list = []
print(my_list)
List Index
Lists are ordered sequences of elements that, like all other ordered containers in Python, are indexed
with a starting index of 0. We supply the index (an integer) inside square brackets ([]) to access an
element in a list. Nested indexing is used to retrieve nested listings.
Attempting to access indexes beyond the limit will result in an IndexError. The index must be a
positive integer. We can’t use floats or other kinds because it will cause a TypeError.
Example
# nesting list
nested = ['Values', [1, 2, 3], ['Marks']]
print(nested[0][0])
print(nested[1][0])
print(nested[1][2])
print(nested[2][0])
# IndexError exception
print(my_list[10])
Output:
List value at index 1: B
List value at index 2: Car
List value at index 4: Egg
V
1
3
Marks
ERROR!
Traceback (most recent call last):
File "<string>", line 20, in <module>
IndexError: list index out of range
To alter an item or a range of elements, we can use the assignment operator ‘=’. We can change a list
item by putting the index or indexes in square brackets on the left side of the assignment operator (like
we access or slice a list) and the new values on the right.
Example
names[2] = 'Lily'
print('Updated List:', names)
names[3] = 'Han'
print('Updated List:', names)
Output:
Original List: ['Ricky', 'Tim', 23, 100.23, 'Sam', 'Emily']
Updated List: ['Ricky', 'Tim', 'Lily', 100.23, 'Sam', 'Emily']
Updated List: ['Ricky', 'Tim', 'Lily', 'Han', 'Sam', 'Emily']
Updated List: ['Ricky', 'A', 'B', 'C', 'D', 'E']
Example
num = [1, 2, 3, 4]
print('Original List:', num)
num.append(5)
print(num)
num.extend([6, 7, 8])
print(num)
Ouptut:
Original List: [1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8]
We can insert one item at a time using the insert() method, or we can insert numerous things by
squeezing them into an empty slice of a list. Unlike the append() function, which accepts only one
argument, insert() function requires two arguments -> (position, value)
Example
num = [1, 2, 5, 6]
print('Original List:', num)
num.insert(2, 3)
print(num)
num.insert(3, 10)
print(num)
Output:
Original List: [1, 2, 5, 6]
[1, 2, 3, 5, 6]
[1, 2, 3, 10, 5, 6]
Delete/Remove List Elements
There are three methods for eliminating items from a list:
Keyword del
Using the keyword del, we can remove one or more entries from a list. It has the ability to completely
remove the list.
num = [1, 2, 3, 4, 5, 6]
print('Original List:', num)
Output:
Original List: [1, 2, 3, 4, 5, 6]
[1, 2, 4, 5, 6]
[1, 2, 4]
Traceback (most recent call last):
File "<string>", line 19, in <module>
ERROR!
NameError: name 'num' is not defined. Did you mean: 'sum'?
The Python remove() method returns None after removing the first matching element from the list. A
ValueError exception is thrown if the element is not found in the list.
num.remove('t')
print(num)
num.remove('n')
print(num)
Output:
Original List: ['p', 'y', 't', 'h', 'o', 'n']
['p', 'y', 'h', 'o', 'n']
['p', 'y', 'h', 'o']
The pop() function can also be used to delete and return a list element. If no index is specified, the
Python pop() method removes and returns the list’s final item. When attempting to remove an index
that is outside the range of the list, an IndexError is raised.
Output:
Original List: ['Mobile', 'Laptop', 'AI', '5G', 'ML']
Item popped: ML
['Mobile', 'Laptop', 'AI', '5G']
Item popped: 5G
['Mobile', 'Laptop', 'AI']
Item popped: Laptop
['Mobile', 'AI']
Also by assigning an empty list to a slice of elements, we can delete elements from a list. For example,
alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print('Original List:', alpha)
alpha[2:5] = []
print(alpha)
Output:
Original List: ['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'f', 'g']
Methods Description
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be
updated. Tuples can be thought of as read-only lists. For example –
Create Tuple
To create a tuple with only one item, you have to add a comma after the item,
otherwise Python will not recognize it as a tuple
output:
Syntax: tuple_name[index_number]
Output:
('abcd', 786, 2.23, 'john', 70.2)
Access index element of 0: abcd
Access index element of 3: 2.23
But there is a workaround. You can convert the tuple into a list, change the
list, and convert the list back into a tuple.
Syntax: Temp_variable=list(tupple_variable)
Output:
tupple Value: ('apple', 'banana', 'cherry')
('apple', 'kiwi', 'cherry')
['apple', 'kiwi', 'cherry']
tuple = (12, 23, 36, 20, 51, 40, (200, 240, 100))
This last element, which consists of three items enclosed in parenthesis, is known as a
nested tuple since it is contained inside another tuple.
employee = ((10, "Itika", 13000), (24, "Harry", 15294), (15, "Naill", 20001), (40, "Peter", 16395))
print(employee)
print(employee[0][1])
print(employee[1][1])
print(employee[2][1])
print(employee[3][1])
Ouptut:
((10, 'Itika', 13000), (24, 'Harry', 15294), (15, 'Naill', 20001), (40, 'Peter', 16395))
Itika
Harry
Naill
Peter
Difference between lists and tuples
The key difference between tuples and lists is that while tuples are immutable
objects, lists are mutable. This means tuples cannot be changed while lists can be modified.
Tuples are also more memory efficient than the lists.