Chapter 4: Working with Lists and Dictionaries
4.1 Introduction to List
A list is a data type that holds an ordered sequence of items. Lists in Python are mutable, meaning you can modify them after creation.
Lists can hold various data types, including integers, floats, strings, tuples, or even other lists.
Examples of Lists
python
Copy code
list1 = [2, 4, 6, 8, 10, 12] # List of integers
list2 = ['a', 'e', 'i', 'o', 'u'] # List of characters
list3 = [100, 23.5, 'Hello'] # Mixed data types
list4 = [['Physics', 101], ['Chemistry', 202]] # Nested list
Accessing Elements in a List
Each element has an index starting from 0.
Negative indexing can access elements from the end.
python
Copy code
list1 = [2, 4, 6, 8, 10, 12]
print(list1[0]) # Output: 2
print(list1[-1]) # Output: 12
4.2 List Operations
Lists support various operations, allowing modification and querying of contents.
4.2.1 Concatenation
Using the + operator, you can join two lists.
python
Copy code
list1 = [1, 3, 5]
list2 = [2, 4, 6]
print(list1 + list2) # Output: [1, 3, 5, 2, 4, 6]
4.2.2 Repetition
The * operator allows repetition of list elements.
python
Copy code
list1 = ['Hello']
print(list1 * 4) # Output: ['Hello', 'Hello', 'Hello', 'Hello']
4.2.3 Membership
The in operator checks for the presence of an element.
python
Copy code
list1 = ['Red', 'Green', 'Blue']
print('Green' in list1) # Output: True
print('Cyan' in list1) # Output: False
4.2.4 Slicing
Slicing allows selection of sublists using [start:end:step].
python
Copy code
list1 = ['Red', 'Green', 'Blue', 'Yellow']
print(list1[1:3]) # Output: ['Green', 'Blue']
print(list1[::-1]) # Output: ['Yellow', 'Blue', 'Green', 'Red']
4.3 Traversing a List
Using loops like for or while to access each element.
python
Copy code
list1 = ['Red', 'Green', 'Blue']
for color in list1:
print(color)
4.4 List Methods and Built-in Functions
Python provides many methods and functions to manage lists.
Common Methods
len(): Returns the number of elements.
append(): Adds an item at the end.
extend(): Appends items from another list.
insert(): Adds an item at a specific position.
remove(): Removes the first occurrence of a value.
pop(): Removes and returns an element by index.
sort(): Sorts the list in place.
reverse(): Reverses the list in place.
4.5 List Manipulation
Python supports creating lists, modifying elements, deleting items, and sorting.
Example Program for List Manipulation:
python
Copy code
myList = [22, 4, 16, 38, 13]
myList.append(45) # Adds 45 to the list
myList.sort() # Sorts the list in ascending order
print(myList) # Output: [4, 13, 16, 22, 38, 45]
4.6 Introduction to Dictionaries
A dictionary is a collection of key-value pairs where keys are unique and immutable.
Each item in a dictionary is a pair separated by a colon (:), and items are separated by commas.
Creating a Dictionary
python
Copy code
dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92}
4.7 Traversing a Dictionary
Access items using for loops with .items().
python
Copy code
for key, value in dict1.items():
print(key, ":", value)
4.8 Dictionary Methods and Built-In Functions
Key functions and methods to work with dictionaries:
keys(): Returns a list of keys.
values(): Returns a list of values.
items(): Returns a list of tuples (key-value pairs).
get(): Returns the value of a specified key.
update(): Adds key-value pairs from another dictionary.
4.9 Manipulating Dictionaries
Dictionaries are mutable, allowing addition, modification, and deletion of items.
python
Copy code
dict1 = {'Mohan': 95, 'Ram': 89}
dict1['Suhel'] = 92 # Adding new key-value pair
dict1['Ram'] = 90 # Modifying value
del dict1['Mohan'] # Deleting a key-value pair