A list is a collection of values that can be of any data type (e.g. integers, strings, floats, etc.). Lists are ordered and mutable, meaning that you can add, remove, or change elements within the list. Lists are represented by square brackets [].
For example:
Some common operations for lists include: indexing, slicing, concatenating, checking the length, and sorting.
Creating Lists
Lists in Python are sequences of values and can be created by enclosing a comma-separated list of values in square brackets [].
Here’s an example:
Lists can contain elements of different data types, including other lists.
Operation on Lists
Lists in Python can be manipulated using various operations such as:
Accessing elements: Lists elements can be accessed using indexing, starting from 0 for the first element.
Slicing: A portion of the list can be selected by slicing the list.
Appending: New elements can be added to the end of the list using the append() method.
Inserting: New elements can be inserted at a specific index using the insert() method.
Deleting: Elements can be deleted from the list using the remove() method or the del statement.
Counting: The number of occurrences of an element in a list can be found using the count() method.
Sorting: The elements in a list can be sorted in ascending or descending order using the sort() method.
Reversing: The elements in a list can be reversed using the reverse() method.
Length: The number of elements in a list can be found using the len() function.
Built in function on Lists
Python has several built-in functions for working with lists. Some of the most commonly used are:
len(list): returns the length of the list.
max(list): returns the maximum element in the list.
min(list): returns the minimum element in the list.
sorted(list): returns a sorted list.
sum(list): returns the sum of elements in the list.
list(sequence): converts a sequence into a list.
append(element): adds an element to the end of the list.
insert(index, element): inserts an element at a specified index in the list.
remove(element): removes the first occurrence of an element in the list.
pop(index): removes and returns the element at a specified index in the list.
index(element): returns the index of the first occurrence of an element in the list.
count(element): returns the number of times an element occurs in the list.
len(list)
The len function in Python is used to find the length of a list. It returns the number of items in a list.
Example:
my_list = [1, 2, 3, 4, 5]
len(my_list)
#Output 5
max(list) and min(list)
max(list) returns the maximum value from a list of numbers, while min(list) returns the minimum value from a list of numbers.
Here is an example:
sorted(list)
sorted(list) is a built-in function in Python that takes a list as an argument and returns a sorted version of that list. The sorted list is a new list and does not modify the original list. The sorting is done in ascending order by default, but you can specify a reverse sort by passing reverse=True as an argument.
Example:
sum(list)
The sum function in Python is used to calculate the sum of elements in a list or iterable. It takes one iterable argument and returns the sum of all its elements.
For example:
list(sequence)
list(sequence) is a built-in function in Python that takes an iterable object, such as a string, tuple, or other sequence type, and converts it into a list.
For example:
append(list)
The append() method in Python is used to add an element to the end of a list.
Here’s an example:
insert(index, element)
insert(index, element) is a method in python programming to insert an element at a specified index in a list.
Syntax: list.insert(index, element)
Example:
colors = [“red”, “green”, “blue”]
colors.insert(1, “yellow”)
colors
[‘red’, ‘yellow’, ‘green’, ‘blue’]
In this example, we have a list of colors colors and we used the insert method to insert the element “yellow” at index 1.
remove(element)
The remove method in Python is a method for lists, which removes the first occurrence of a specified element from the list.
Example:
pop(index)
The pop(index) method in Python programming is used to remove the element at the specified index and returns the removed item. This method also modifies the original list. If index is not specified, the method removes and returns the last item.
Example:
index(element)
The index(element) method in python programming returns the index of the first occurrence of the specified element in the list. If the element is not found, it raises a ValueError exception.
Syntax: list.index(element)
Example:
count(element)
The count(element) method returns the number of occurrences of a given element in a list.
Example:
Implementation of Stack
Implementing a stack in Python using a list is straight forward as a list provides a natural way of adding and removing elements in Last-In-First-Out (LIFO) order. To implement a stack, we can use the append() and pop() methods of the list.
Implementation of Queue
In Python, a queue can be implemented using the built-in list data structure. Here are the steps to implement a queue using lists:
Initialize an empty list to represent the queue.
For inserting an element to the queue, use the append() method to add the element to the end of the list. This operation is also known as enqueue.
For removing an element from the queue, use the pop(0) method to remove the first element from the list. This operation is also known as dequeue.
Here is an example implementation of a queue using lists in Python:
Note that the append() and pop() methods have an average time complexity of O(1), making the implementation efficient for most use cases.
Nested List
A nested list is a list object that is an element of another list. The inner lists can contain elements of any data type, including other lists, making it possible to create multidimensional lists.
For example:
Here, list is a 3×3 matrix with 3 nested lists, each representing a row. To access elements in a nested list, use multiple square bracket notations
Dictionaries
A dictionary is a collection of key-value pairs in Python. It is an unordered and mutable data type. The keys in a dictionary must be unique, hashable and immutable, and the values can be of any data type. Dictionaries are defined using curly braces {} and are accessed using square brackets []. To access the value for a particular key, the key is passed inside the square brackets. To add or modify a key-value pair, the key is assigned a value using the assignment operator (=).
Creating Dictionaries
Dictionaries in Python are created using the curly brackets {}. Each key-value pair is separated by a comma ,. The key is mapped to a value using a colon :
dict = {‘key1’:‘value1’, ‘key2’:‘value2’, ‘key3’:‘value3’}
Alternatively, you can use the built-in function dict() to create a dictionary.
dict = dict(key1=‘value1’, key2=‘value2’, key3=‘value3’)
Example
Dictionaries in Python are used to store key-value pairs where keys are unique, and values can be of any data type.
Here’s an example:
Operations on Dictionaries
Dictionaries are mutable and unordered collection of key-value pairs.
Some common operations on dictionaries are:
Accessing items: You can access the values using the keys.
For example, “dict[key]”
Adding items: You can add new items to the dictionary using the syntax “dict[key] = value”.
Removing items: You can remove items from the dictionary using the “del” keyword or the “pop()” method.
Modifying items: You can modify existing items by assigning new values to them.
Getting keys: You can get a list of all keys in the dictionary using the “keys()” method.
Getting values: You can get a list of all values in the dictionary using the “values()” method.
Getting items: You can get a list of all items (key-value pairs) in the dictionary using the “items()” method.
Length: You can find the length of a dictionary using the “len()” function.
Dictionary Method
A dictionary method is a pre-defined function associated with the dictionary data structure in Python programming.
Some common dictionary methods are:
clear() – removes all items from the dictionary.
copy() – returns a shallow copy of the dictionary.
get(key, default) – returns the value of the specified key. If the key is not found, it returns the specified default value.
items() – returns a list of the dictionary’s key-value pairs.
keys() – returns a list of the dictionary’s keys.
values() – returns a list of the dictionary’s values.
update(other_dict) – updates the dictionary with the key-value pairs from another dictionary.
These methods provide a convenient way to perform common operations on dictionaries without writing explicit code.
Built in Functions on Dictionaries
There are several built-in functions for dictionaries, including:
len(dict) – returns the number of key-value pairs in the dictionary.
str(dict) – returns a string representation of the dictionary.
type(object) – returns the type of the object, including dictionaries.
dict.clear() – removes all key-value pairs from the dictionary.
dict.copy() – returns a shallow copy of the dictionary.
dict.get(key, default) – returns the value of the specified key if it exists in the dictionary, otherwise returns the default value.
dict.items() – returns a list of key-value pairs in the dictionary.
dict.keys() – returns a list of keys in the dictionary.
dict.values() – returns a list of values in the dictionary.
dict.update(other_dict) – adds key-value pairs from another dictionary to the current dictionary.
len(dict)
The len() function is used to determine the number of items in a dictionary. It returns the number of key-value pairs in the dictionary.
The syntax for using len() on a dictionary is:
len(dict)
For example:
str(dict)
The str() function is used to convert a data type to a string representation. When applied to a dictionary, the str() function returns a string representation of the dictionary, which is a comma-separated list of key-value pairs enclosed in curly braces.
Example:
dict.clear()
The clear() method is used to remove all the items from a dictionary. The method does not return any value.
For example:
dict.copy()
dict.copy() is a method to create a shallow copy of a dictionary. It returns a new dictionary that is a copy of the original dictionary. The original and the copied dictionaries are separate objects, but the values in the copied dictionary are still references to the same objects as the values in the original dictionary. This means that if you change a value in the original dictionary, the same change will reflect in the copied dictionary as well.
Example:
dict.get(key, default)
dict.get(key, default) is a method used to access a value of a given key in a dictionary. If the key is present in the dictionary, the value corresponding to that key is returned.
If the key is not present, it returns the default value specified in the second argument. If no default value is specified, it returns None.
Example:
dict.items()
dict.items() is a built-in function that returns a view object that displays a list of the dictionary’s (key, value) pairs, as dict_items object. The dict_items object is a dynamic view of the dictionary’s items. This means that changes to the dictionary will be reflected in the view.
Syntax: dict.items()
Example:
dict.keys()
dict.keys() is a built-in method that returns a view object that displays a list of all the keys in the dictionary. This method does not take any arguments.
Example:
Note that the output of dict.keys() is a dict_keys object, which is not a list, but can be converted to a list using the list() function.
dict.values()
dict.values() is a method that returns a list of all the values in the dictionary.
For example:
dict.update(other_dict)
The update() method is used to merge another dictionary into the current dictionary. It adds the elements of one dictionary object to another dictionary object.
The syntax is: dict.update(other_dict), where dict is the original dictionary and other_dict is the dictionary you want to merge into dict. The update() method returns None, it modifies the original dictionary.
Example:
Populating Dictionaries
Populating dictionaries in Python programming refers to adding key-value pairs to a dictionary. This can be done in several ways:
Direct assignment: Using the square brackets [], you can add key-value pairs to the dictionary as follows:
Using update(): You can use the update() method to add multiple key-value pairs to a dictionary:
Using the dict() constructor: You can use the dict() constructor to create a dictionary from a list of tuples or another dictionary:
Using a dictionary comprehension: A dictionary comprehension allows you to create a dictionary from an expression that evaluates to a key-value pair:
Traversing Dictionaries
Traversing dictionaries to looping over the key-value pairs in a dictionary and accessing the values. This can be done using a for loop and the items() method, which returns a list of (key, value) pairs in the dictionary.
Here’s an example:
To buy Python books click the below links
Python Programming
Python Programming 2E
Handbook of Python Programming