7.14 Lists and Dictionary
Python list
·
A
list in Python is an ordered collection of items, which can be of different
types like integers, strings, floats, Booleans etc.
·
It
is a built-in data types which stores multiple data in a single variable.
·
It
is one of the most commonly used data structures in Python, and they are very
flexible because they are mutable (we can change their content after creation).
Creating a List : A list is created by placing items
inside square brackets [ ], separated by commas.
Syntax:
A list is created by placing items
inside square brackets [ ], separated by commas.
Examples:
# A list of integers
numbers = [1, 2, 3, 4, 5]
# A list of strings
fruits = ["apple",
"banana", "cherry"]
# A mixed list (different types of
elements)
mixed_list = [1, "apple",
3.14, True]
# An empty list
empty_list = [ ]
Accessing Elements: We can access elements of a list
using their index. Indexing in Python starts from 0 for the first element.
Syntax:
my_list[index]
Examples:
# Accessing the first element
(index 0)
print(numbers[0]) # Output: 1
# Accessing the second element
(index 1)
print(fruits[1]) # Output: banana
# Accessing the last element
(negative index)
print(mixed_list[-1]) # Output: True
Modifying a List: Since lists are mutable, we can
modify, add, or remove elements after the list is created.
Examples:
# Changing an element by index
numbers[0] = 10
print(numbers) # Output: [10, 2, 3, 4, 5]
# Adding an element at the end of
the list (append)
fruits.append("orange")
print(fruits) # Output: ["apple",
"banana", "cherry", "orange"]
# Inserting an element at a
specific index (insert)
fruits.insert(1,
"grape") # Adds
"grape" at index 1
print(fruits) # Output: ["apple",
"grape", "banana", "cherry", "orange"]
# Removing an element by value
(remove)
fruits.remove("banana")
print(fruits) # Output: ["apple",
"grape", "cherry", "orange"]
# Removing an element by index
(pop)
removed_item = fruits.pop(2) # Removes "cherry" at index 2
print(fruits) # Output: ["apple",
"grape", "orange"]
print("Removed:",
removed_item) # Output: Removed: cherry
List Length: We can find the number of elements
in a list using the len( ) function.
Syntax:
len(my_list)
Example:
print(len(fruits)) # Output: 4
Looping through list: We can loop through the list
elements using the for loop to print all the elements one by one.
Example:
# List of fruits
fruits = ["apple",
"banana", "cherry", "orange"]
# Looping through the list
for fruit in fruits:
print(fruit)
List Slicing: We can access a sub list or slice
from a list by specifying a start and end index.
Syntax:
my_list[start:end]
·
start: The index to start from
(inclusive).
·
end: The index to end at (exclusive).
Examples:
# A list of strings
fruits = [“apple”, “grape”,
“cherry”, “orange”]
# Slicing from index 1 to 3 (does
not include index 3)
print(fruits[1:3]) # Output: ['grape', 'cherry']
# Slicing from the beginning to
index 2
print(fruits[:2]) # Output: ['apple', 'grape']
# Slicing from index 2 to the end
print(fruits[2:]) # Output: ['cherry', 'orange']
# Slicing the entire list (same as
making a copy)
print(fruits[:]) # Output: ['apple', 'grape', 'cherry',
'orange']
List Concatenation and Repetition :
We can concatenate
(join) lists using the + operator and repeat a list using the * operator.
Examples:
# Concatenating two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined) # Output: [1, 2, 3, 4, 5, 6]
# Repeating a list
repeated = list1 * 2
print(repeated) # Output: [1, 2, 3, 1, 2, 3]
List Comprehension: It is a concise way to create lists
by applying an expression to each item in an iterable.
Syntax:
[expression for item in iterable if
condition]
Example:
# Creating a list of squares from 0
to 4
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
# Using a condition to filter even
numbers
even_numbers = [x for x in
range(10) if x % 2 == 0]
print(even_numbers) # Output: [0, 2, 4, 6, 8]
Nested Lists : Lists can contain other lists as
elements. These are called nested lists.
Example:
nested_list = [1, [2, 3], 4, [5,
6]]
print(nested_list[1]) # Output: [2, 3]
print(nested_list[1][0]) # Output: 2
List Methods: Here are some common methods that
can be used with lists:
- append(item)
— Adds an item to the end of the list.
- insert(index,
item) — Inserts an item at a specified index.
- remove(item)
— Removes the first occurrence of the item from the list.
- pop(index)
— Removes and returns the item at the specified index.
- sort()
— Sorts the list in ascending order.
- reverse()
— Reverses the order of elements in the list.
- clear()
— Removes all items from the list.
fruits = ["apple",
"banana", "cherry"]
fruits.sort() # Sorts the list alphabetically
print(fruits) # Output: ['apple', 'banana', 'cherry']
fruits.reverse() # Reverses the list
print(fruits) # Output: ['cherry', 'banana', 'apple']
fruits.clear() # Clears all items in the list
print(fruits) # Output: [ ]
Python Dictionary
·
A
dictionary in Python is an unordered collection of key-value pairs.
·
Each
item in a dictionary has a unique key and a corresponding value.
·
It
is one of the most versatile and widely used data structures in Python.
Creating a Dictionary
·
A
dictionary is created by placing key-value pairs inside curly braces {},
separated by commas.
·
The
key and value are separated by a colon : .
Syntax:
my_dict = {key1: value1, key2:
value2, key3: value3, ...}
Example:
# A dictionary of fruits with their
colors
fruit_colors = {"apple":
"red", "banana": "yellow", "cherry":
"red"}
Accessing Dictionary Values : We can access the value associated
with a key by using square brackets [ ] with the key inside.
Syntax:
my_dict[key]
Example:
fruit_colors = {"apple":
"red", "banana": "yellow", "cherry":
"red"}
print(fruit_colors["apple"]) # Output: red
·
If
we try to access a key that doesn’t exist in the dictionary, it will raise a
KeyError.
·
To
handle missing keys safely, we can use the get() method, which returns None if
the key is not found (or a default value you specify).
Example:
print(fruit_colors.get("orange",
"Not found")) # Output: Not
found
Adding or Modifying Items : To add a new key-value pair or
modify an existing value in a dictionary, we simply assign a value to a key.
Examples:
fruit_colors["orange"] =
"orange" # Adds a new
key-value pair
fruit_colors["banana"] =
"green" # Modifies the value
for the key "banana"
print(fruit_colors)
Ouput:
{'apple': 'red', 'banana': 'green',
'cherry': 'red', 'orange': 'orange'}
Removing Items : We can remove items from a
dictionary using the del keyword or the pop() method.
- del
statement: Removes the item with the specified key.
- pop(
) method: Removes and returns the value associated with a specified key.
Examples:
# Using del to remove a key-value
pair
del
fruit_colors["cherry"]
# Using pop() to remove a key-value
pair and get the value
removed_value =
fruit_colors.pop("apple")
print(fruit_colors) # Output: {'banana': 'green', 'orange': 'orange'}
print("Removed value:",
removed_value) # Output: Removed value:
red
Accessing All Keys, Values, and
Items
- keys(
) method: Returns a view object containing all the keys.
- values(
) method: Returns a view object containing all the values.
- items(
) method: Returns a view object containing all the key-value pairs as
tuples.
Examples:
fruit_colors = {"apple":
"red", "banana": "yellow", "cherry":
"red"}
# Accessing all keys
print(fruit_colors.keys()) # Output: dict_keys(['apple', 'banana',
'cherry'])
# Accessing all values
print(fruit_colors.values()) # Output: dict_values(['red', 'yellow',
'red'])
# Accessing all items (key-value
pairs)
print(fruit_colors.items()) # Output: dict_items([('apple', 'red'),
('banana', 'yellow'), ('cherry', 'red')])
Dictionary length : To determine the numbers of
key:values present in the dictionary, len() function is used.
Example:
# A dictionary of fruits and their
colors
fruit_colors = {"apple":
"red", "banana": "yellow", "cherry":
"red", "orange": "orange"}
# Getting the length of the
dictionary
length = len(fruit_colors)
print("Length of the
dictionary:", length)
Looping through Dictionary: We can loop through the dictionary
using the for loop to print all the elements one by one.
Examples:
fruit_colors = {"apple":
"red", "banana": "yellow", "cherry":
"red", "orange": "orange"}
# Looping through dictionary keys
for key in fruit_colors:
print(key)
# Looping through dictionary values
for value in fruit_colors.values():
print(value)
# Looping through key-value pairs
for key, value in
fruit_colors.items():
print(f"Key: {key}, Value: {value}")
# Looping through with index
for index, (key, value) in
enumerate(fruit_colors.items()):
print(f"Index {index}: Key = {key}, Value = {value}")
Dictionary Comprehension : Just like list comprehension, we
can also use dictionary comprehension to create dictionaries.
Syntax:
{key: value for key, value in
iterable if condition}
Example:
# Creating a dictionary with
squares of numbers
squares = {x: x**2 for x in
range(5)}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Nested Dictionaries : A dictionary can contain other
dictionaries as values, creating nested dictionaries.
Example:
# A dictionary with nested
dictionaries
students = {
"John": {"age": 25, "grade":
"A"},
"Anna": {"age": 22, "grade":
"B"},
}
# Accessing nested dictionary
values
print(students["John"]["age"]) # Output: 25
print(students["Anna"]["grade"]) # Output: B
Checking if a Key Exists : We can check if a key exists in a
dictionary using the in keyword.
Example:
fruit_colors = {"apple":
"red", "banana": "yellow", "cherry":
"red"}
# Checking if a key exists
if "apple" in
fruit_colors:
print("Apple is in the dictionary")
Merging Dictionaries : We can merge two dictionaries using
the update() method or the | operator (Python 3.9+).
- Using
update(): Merges another dictionary or iterable of key-value pairs into
the original dictionary.
- Using
| operator (Python 3.9+): Combines two dictionaries into a new one.
Examples:
# Using update()
dict1 = {"apple":
"red", "banana": "yellow"}
dict2 = {"cherry":
"red", "orange": "orange"}
dict1.update(dict2)
print(dict1) # Output: {'apple': 'red', 'banana':
'yellow', 'cherry': 'red', 'orange': 'orange'}
# Using | operator (Python 3.9+)
dict3 = dict1 | dict2
print(dict3) # Output: {'apple': 'red', 'banana':
'yellow', 'cherry': 'red', 'orange': 'orange'}
Dictionary Methods : Here are some common dictionary
methods:
- clear()
— Removes all items from the dictionary.
- copy()
— Returns a shallow copy of the dictionary.
- fromkeys()
— Creates a dictionary with specified keys and a default value.
- get()
— Returns the value for a key, or None if the key doesn't exist.
- pop()
— Removes and returns the value for a specified key.
- popitem()
— Removes and returns a random key-value pair.
- setdefault()
— Returns the value of a key, and if the key doesn’t exist, inserts it
with a default value.
Example:
fruit_colors = {"apple":
"red", "banana": "yellow", "cherry": "red"}
# Using popitem()
item = fruit_colors.popitem()
print(item) # Output: ('cherry', 'red')
print(fruit_colors) # Output: {'apple': 'red', 'banana':
'yellow'}
7.15 Uses of Library functions :
String Functions (center, upper, lower, Len), Numeric and mathematical (sum,
pow, round, abs, sqrt, Int)