IV Unit
IV Unit
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
Add/Change List Elements
Lists, unlike strings and tuples, are mutable, which means that their elements can be altered. There are
few methods by which we can add or change the elements inside the list. They are as follows –
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']
The built-in append() function can be used to add elements to the List. The append() method can only
add one element to the list at a time. We can use the extend() function to add multiple elements to the
list.
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]
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.
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
Python Tuples
Python tuple is another sequence data type that is similar to a list. A Python tuple consists of a
number of values separated by commas. Unlike lists, however, tuples are enclosed within
parentheses.
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
Python Dictionaries
Dictionaries are used to store data values in key:value pairs.
Dictionaries are written with curly brackets, and have keys and values:
thisdict={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Dictionary length: 3
<class 'dict'>
Accessing Datas
You can access the items of a dictionary by referring to its key name, inside
square brackets:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["model"])
print(thisdict.get("model"))
Output:
Mustang
Mustang
Get Keys
The keys() method will return a list of all the keys in the dictionary.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car)
print(car.keys())
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
dict_keys(['brand', 'model', 'year'])
Get Values
The values() method will return a list of all the values in the dictionary.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car)
print(car.values)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
dict_values(['Ford', 'Mustang', 1964])
Get Items
The items() method will return each item in a dictionary, as tuples in a list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car)
print(car.items())
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
Change Values
You can change the value of a specific item by referring to its key name:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car) # Before change
car["year"] = 2018
print(car) #After Change
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
Update Dictionary
The update() method will update the dictionary with the items from the given
argument.
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
{'brand': 'Ford', 'model': 'Mustang', 'year': 2023}
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a
value to it:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car)
car["Colour"]="Red"
print(car)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'Colour': 'Red'}
Removing Items
The pop() method removes the item with the specified key name:
car= {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.pop("model")
print(car)
Output
{'brand': 'Ford', 'year': 1964}
Example
The popitem() method removes the last inserted item (in versions before 3.7, a
random item is removed instead):
car= {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.popitem()
print(car)
Output:
{'brand': 'Ford', 'model': 'Mustang'}
Lists are best for sequential data, while dictionaries are tailored for data
retrieval by specific identifiers.