Showing posts with label Dictionaries. Show all posts
Showing posts with label Dictionaries. Show all posts

Thursday, February 29, 2024

DICTIONARIES IN PYTHON

Python Dictionaries

Introduction

  • Definition and Structure
  • Key Characteristics
  • Accessing Values
  • Dictionary Methods
  • Adding and Modifying Entries
  • Removing Entries
  • Dictionary Comprehensions
  • Iterating Over Dictionaries
  • Nested Dictionaries
  • Dictionary Operations and Comparisons

Python dictionaries and their uses will be covered in this section. Dictionary data is diverse and easy to arrange and retrieve. They help link relevant data for better data management. This chapter covers creating, accessing, and modifying dictionaries. Dictionaries are more flexible than lists because their keys can be any data type. With dictionaries, information storage is nearly infinite.

Python calls dictionaries “dict”; other languages call them “hashes”. In a dictionary, indexes are called “keys” and always have a value, therefore they are called key-value pairs. Braces {} are used to type dictionaries. In this chapter, we will look at various Python dictionary examples and learn about dictionaries in Python.

Dictionary

Python dictionaries and their uses will be covered in this section. Dictionary in Python is data that is diverse and easy to arrange and retrieve. They help link relevant data for better data management. This chapter covers creating, accessing, and modifying dictionaries. Dictionaries are more flexible than lists because their keys can be any data type. With dictionaries, information storage is nearly infinite.

Python calls dictionaries “dict”; other languages call them “hashes”. In a dictionary, indexes are called “keys” and always have a value, therefore they are called key-value pairs. Braces { } are used to type dictionaries. below is the basic code for a dictionary in Python or how we create a dict in Python.

In the above code we can see that we created a dictionary the “hinting” using the dict() function and we can verify that it creates a dictionary because when we print it, it prints the empty braces {} which represent the dictionary.

Now let’s look at that type of dictionary which we mainly create in Python programming for our problem-solving. 

The Python code above creates a dictionary named “mydog” with a key-value pair. We also see that the keys are strings, which we've covered, and may be any type.

Python dictionaries fetch values for keys. A colon links each dictionary key to its value, while commas divide key-value pairs. Dictionaries may store any number of key-value pairs, making data organization and access flexible.

Real-World Example of Python Dictionary Usage

To better understand the Python Dictionary let’s take an example suppose we are building a student management system for a school using Python dictionaries to store and manage student information. Each student has unique attributes such as name, age, grade, and subjects enrolled. Here’s how we can use Python dictionaries for this purpose:

# Dictionary to store student information

students = {

    "101": {"name": "Alice", "age": 15, "grade": 10, "subjects": ["Math", "Science", "English"]},

    "102": {"name": "Bob", "age": 14, "grade": 9, "subjects": ["History", "Geography", "Math"]},

    # Additional students can be added similarly

}

With this dictionary structure, we can easily access and manipulate student information. For instance, to add a new student we just need to write the below code:

new_student = {"name": "Charlie", "age": 16, "grade": 11, "subjects": ["Physics", "Chemistry", "Biology"]}

students["103"] = new_student

To update the subjects for a specific student, let’s say Bob we just need to write the following code:

students["102"]["subjects"].append("Computer Science")

To display the subjects enrolled by a particular student, such as Alice we need to write the below code:

alice_subjects = students["101"]["subjects"]

print("Subjects enrolled by Alice:", alice_subjects)

Furthermore, we can iterate over the dictionary to perform operations on all students, such as calculating the average age or printing the names of students in a particular grade.

In conclusion, Python dictionaries provide an efficient way to organize and manage student information in a student management system, allowing easy access, update, and retrieval of student data.

Simple Dictionary

Let's examine a basic dictionary. A basic dictionary holds item-specific information. Consider a dictionary named alien with multiple colors and point values. Let's look at Python code to understand.

In the above code, we can see that alien1 stores the alien’s color and point values, and we can access them using square brackets and passing a key inside them.

Accessing Values in a Dictionary

As seen above, we use the dictionary's name and the key in square brackets to obtain an item or value. This tells Python to return the key value means we are accessing values in the dictionary Python.

If we made a game with aliens and earned points by shooting them, we could indicate how many points the player should earn using the code below.

The preceding code stores key “points” values from the dictionary in the new_points variable. After that, we transform the integer value to a string and utilize it to build a statement about the player's points, which is reported to the console. 

Adding New Key-Value Pairs

Python dictionaries are dynamic, so we can quickly add new key-value pairs. Steps to add a new entry: Open square brackets and enter the new key name after specifying the dictionary name. We use the assignment operator to link the key and its value after closing the square brackets. Once this is done, printing the dictionary again will show the updated key-value pair. Coding will demonstrate this technique.

The following code snippet prints the dictionary after it has been formed with two keys and values on the first line, updated with new keys and values on the second line, and finally printed.

Dictionaries vs. Lists

Item order is store-like in the list but not in the dictionary. We use a square bracket with list_name to access the first item, which is list_name[0], but the dictionary has no first value or index. The order of elements in a list determines whether two lists are the same, whereas, with dictionaries, it doesn't matter what key-value pairs are written. For clarity, let's examine Python code for both.

In the above code, we can see that list1 and list2 have the same items but they are in different orders, and when we compare them using the equal to operator, they print False. on the other hand, dict1 and dict2 have the same key-value pairs in different order, but when we compare them using the equal to operator, the dictionary prints "true," which shows that both dictionaries are equal. If sorted, dictionaries might be lists, but they're not.

If we access a key not in the dictionary, we receive a KeyError, which is similar to the list's “out-of-range” IndexError. Python code that accesses a key not in the dictionary shows the error.

The Python interpreter displays the anticipated KeyError error in the above code.

Python dictionaries may take any key-value pair, enabling sophisticated data organization. Consider creating a birthday management program for pals. We can conveniently store their information in a dictionary using each friend's name as a key and their birthdate as a value. Simply enter the new friend's name and birthdate to update the dictionary. Let's code this application in Python. 

The code snippet creates a dictionary called "birthdays" with names as keys and birthdays as values. The program searches the dictionary for user-entered names. If the birthdate is present, it is printed out; otherwise, the user is requested to input it and alerted that it is missing. The new name-birthday pair is added to the lexicon. New names are added to the dictionary in the final output, validating the modification.

Similar square bracket syntax with the assignment operator is used to add a value to a dictionary. However, the dictionary key must be given in square brackets to designate where to add the new value.

Modifying Values in a Dictionary

We can easily update or modify the dictionary value by using the name of the dictionary, writing the key in square brackets, closing the brackets, and using the assignment operator (=) to assign the new value to the key. See the Python code for clarity.

First, we define a dictionary named ‘alien1’ in the code. After assigning the new value to the key ‘player name’ using the aforementioned instructions, we print the alien1 dictionary again and observe that the player name has changed from “Alex” to “Rohit”.

For a more complex situation, add the speed property to the "alien1" dictionary to track an alien with variable speed. In this configuration, we save the alien's speed and subsequently determine its ability to go in the appropriate direction.

At the start of the program, we declare a dictionary with x, y position, and speed keys and values. The alien2 dictionary's x position is printed next. If the speed key is sluggish, we create a variable named x_increment and set it to 5. We next verify if the speed key's value is ‘medium’ and utilize the x_increment variable again, this time with 10. Only the ‘fast’ speed remains after verifying the ‘slow’ and ‘medium’ speeds, therefore we use the else condition to put 15 on the x_increment variable. After testing the condition, we change the x_position by adding the current value and the condition value. Last, we report the updated x_position value to the output, showing the old and new values.

Removing Key-Value Pairs

When a dictionary item is unnecessary, we can use "del". It deletes a dictionary key-value pair. We specify the dictionary name and key to remove. This strategy is better explained with an example.

In the above code, we can see that before using the “del” statement we have three key-value pairs in the dictionary but when we use the “del” statement to remove the speed key and its value from the dictionary it removes it and we can verify this by printing the dictionary again.

A Dictionary of Similar Objects

We've mostly saved object-related information in dictionaries. Dictionaries may arrange and store homogeneous data about many things. Let's create a dictionary with comparable data entries.

The dictionary example shows a huge vocabulary arranged over numerous lines for clarity. The dictionary's keys are people's names and their values are their programming languages. For readability, such dictionaries must have a consistent indentation, especially when they span numerous lines. This includes naming the dictionary after the assignment operator, opening the brace, pushing enter, and indenting the next lines by one level (typically four spaces). Key-value pairs should be indented to match the initial pair and separated by commas. After finishing the dictionary, the closing brace is placed on a new line indented to match the key-value pairs. This layout assures dictionary definition clarity and structure. Examine a Python code sample to find which programming language each user likes.

In the above code, we first created a dictionary then we printed the output which shows Rohit’s favorite language using print statement.

The keys(), values(), and items() Methods

Keys(), values(), and items() are dictionary methods that return lists of keys, values, and key-value pairs. Please note that these methods do not return lists of values. They cannot be modified or appended like lists. Instead, they give iterable representations of the dictionary's keys, values, and objects without modifying the underlying dictionary. This difference preserves the dictionary's structure while making its components easy to retrieve. A for loop works with these data types. How does the for loop work with a dictionary?

The for loop in the code above iterates across all alien1 dictionary values. For loops can iterate over keys and key-value pairs. We pass keys to iterate.keys() with a dictionary in the for loop iterates key-value pairs.items() in the for loop.

The keys(), values(), and items() methods can loop over the dictionary's keys, values, and the entire key-value combination. Note that items() returns a key-value tuple. Tuples exist for every key and value.

To create a list from dictionary keys or values, we must feed its list-like return value to the list(). Let's see the Python code for clarity.

List() returns ['color', 'age'] from keys()'s dict_keys value in the list(spam.keys()) line. We may alternatively output values as a list using list().

In a for loop, we may assign keys and values to different variables using several assignment methods. This Python code should be examined.


In the above code, we can see that in the for loop we use two variables k, and v to iterate over the dictionary’s keys and values and print them using variables.

Checking Whether a Key or Value Exists in a Dictionary

The "in" and "not in" operators can be used to check dictionaries for a specific key or value. These operators make it easy to check for a key or value without iterating over the dictionary. If a key or value is in a dictionary, the "in" operation returns True; otherwise, False. The "not in" operator returns True if the key or value is not in the dictionary and False otherwise. This capability streamlines membership testing, making dictionaries more versatile. Like a list operation, we verify if a value is in the list. Take a peek at Python code to understand.


We employ “in” and “not in” operators in different scenarios in the aforementioned programs. The “key” “color” in the above dictionary is checked for spam keys first. It outputs True since it exists. The next code checks if ‘green’ is in the spam vocabulary and displays False because it is not. The next code uses the dictionary key. We verify ‘name’ in the spam dictionary keys in the fourth block. The code above outputs False if it is present and True otherwise. The same goes for dictionary values. The last piece of the code checks if ‘name’ is in the spam dictionary's key or value and outputs True if it is, False otherwise.

Python dictionary comprehension

An efficient and readable technique to build dictionaries with only one line of code is Python's dictionary comprehension.

The above creates a dictionary where the keys are numbers from 1 to 5, and the values are their squares. It is also the advanced dictionary in Python or we can say it is the advanced method to create a dictionary in Python.


The get() Method

It takes time to check if a key is in the dictionary before retrieving its value. Luckily, dictionaries provide a get() method that takes two parameters: the value to obtain and a backup value in case the key is incorrect. Take a peek at Python code to understand. We can also use the get() method for accessing values in the dictionary in Python.

We obtain 0 mangoes since there are no ‘mangoes’ in the picnicItems dictionary and we pass 0 to the get() function. Without the get() function, the code will create an error message like this:

The setdefault() Method
It is frequently necessary to set a value for a key in a dictionary only if it is empty. In normal technique, the code looks like the below demo. 

The "setdefault()" function can reduce this operation to one line of code, saving time. The second parameter defines the key to be checked and assigns a value if none exists. This method accepts two parameters. "setdefault()" puts the key-value pair into the dictionary and returns the value if the key is not in it. Adding new key-value pairs to the dictionary is easier with this method. We'll use the following code snippet to demonstrate this.

'color' is now associated with this value. When attempting to reassign the color using the setdefault() method to "white" in the subsequent line of code, the value of the key remains 'black'. This is because the dictionary already contains a key named 'color', and the setdefault() method does not alter existing key-value pairs.

The setdefault() method provides a convenient way to confirm the presence of a key within a dictionary. Consider a brief program demonstrating its usage to tally the occurrences of each letter within a string. 

The for loop of the program iterates over the string "message," counting each character's frequency. The setdefault() function checks if each character is a dictionary key and initializes it to 0 if not. This method avoids mistakes while incrementing character counts using count[character] = count[character] + 1.

The output shows character occurrences in the string. Two lowercase "c," thirteen space characters, and one uppercase "A" are visible.


Looping Through a Dictionary

Python dictionaries can store a few to millions of key-value pairs, making them adaptable data storage. Python has numerous dictionary iteration algorithms for varied datasets. You can cycle over all key-value pairs directly, iterate over keys or values separately, or use a mix of these to retrieve specific dictionary items.

Looping Through All Key-Value Pairs

As we saw before, we can retrieve dictionary key-value pairs using any key or value. Let's see both code examples. The code below loops over the dictionary's key and value and prints them. 

The code initializes a dictionary and iterates through its key-value pairs using a for loop. Two variables store each pair's key and value in the loop. Choose these variable names freely. This loop iterates across key-value pairs from the dictionary's items() function. The first variable stores the key, while the second stores the value. Key and value are shown using two print statements. This Python example shows how to retrieve and display dictionary contents. 

In the above code, we can see that we print the favorite programming language of the person using the same method we describe above.

Looping Through a Dictionary’s Keys in Order

While dictionaries lack a fixed order for their contents, this usually doesn't matter because keys can properly retrieve values. To retrieve keys in a specified sequence, they can be sorted first. The sorted() method sorts the dictionary's keys. Iterating over these sorted keys in a loop retrieves the items in order. This strategy is shown in the Python code below.

Note: -  the sorted() function can also sort the values of a dictionary just like keys. The code is also written below.

Nesting

Nesting dictionaries in a list or vice versa is sometimes needed. Nesting might entail embedding dictionaries or lists within dictionaries. Encapsulating a dictionary within another is conceivable. This layering capability is powerful in programming, but it's complicated to understand.


A list of Dictionaries

In this section, we will create a list of dictionaries in Python. Let's say we constructed a dictionary with a variety of information about one type of data or item, but it has no place for a second type, reducing data space. How do we handle this? Make a list of any dictionary-related variable and include all dictionary information in it. For example, let us have a dictionary called alien_0 with a certain type of information. If we want to store another alien_1 with the same information, we can create another dictionary to store its information, but if we have many alien dictionaries and want to show them all at once, we store them in a list and use a for-loop to print them. Let's examine Python code for clarity.

In the above code, we created three alien dictionaries that store the same data, so we cannot store them in one dictionary (which is a problem). Instead, we store them in three dictionaries, list them, and use a for loop to print them all at once.

A more realistic and practical example is automatically storing more than three alien dictionaries in the list. The example code below creates 30 aliens with the same key and value for speedy generation and stores them in an empty list.

As demonstrated above, we gave Python instructions to perform the for loop a specific number of times after creating an empty list by using the range() method. Each time the loop completes one iteration it creates a new dictionary called new_alien. Then in the next line with the help of the append() method, we add these created dictionaries to the aliens' dictionary.

In the next section of the code, we print the first five alien dictionaries from the alien's list using for loop, and at last, we print the total number of alien dictionaries we created to check that we have 30 new_alien dictionaries.

Let’s suppose from the above example some aliens change their color and move much faster as they progress. To accomplish this task, we utilize a combination of a for loop and if statement in the provided code. For instance, suppose we aim to alter the attributes of the first three aliens, changing their color from green to yellow, their speed from slow to medium, and their points from 5 to 10. By iterating through the list of aliens, we can implement these modifications based on specific conditions specified within the if statement. We can do this by adding the following lines code after we created and append all 30 aliens. For better understanding let’s write the whole code with this extra code.

A List in a Dictionary

When ordering pizza, a list may not convey enough information. A list could merely include toppings, excluding important subtleties. A dictionary provides a more complete description. A more complete pizza order might be represented by a dictionary with key-value pairs for crust type, toppings, size, and special instructions.

Consider a pizza shop that stores your dough and topping preferences. The dictionary value "toppings list" is connected with the key "toppings." Different values make up the toppings. Let's view the code for clarity. 

We constructed a dictionary called “pizza” to store order information in the above code. The pizza dictionary key ‘crust’ has the value ‘thick’. The next key value is a list. This list contains topping statistics. Before making the pizza, we summarize the order for print. As toppings have a list as a value, we must use the “for” loop to display and retrieve their key values.

When connecting several items with a single key, we can nest a list in a dictionary. For instance, update our preferred language dictionary. In this new dictionary, users may have many favorite languages. Our dictionary would assign each person a list of languages instead of one. We may go over each person's language using a nested for loop in the dictionary loop. This code sample shows:

The code shows that the dictionary keeps each key's (name) matching values. Certain keys, such as preferred language, contain single values, while others are listed. Each dictionary value is a list, therefore we use "languages" in the initial for loop to run over them. We use another for loop in the main loop to go through each person's favorite languages.

Note: Avoid deep nested lists and dictionaries. The examples show adequate layering, but excessive nesting can make code hard to comprehend and maintain. In such circumstances, simpler solutions are usually best.


A Dictionary in a Dictionary

Nesting dictionaries may easily complicate coding. Consider a website with several users with distinct usernames. In such circumstances, usernames can be dictionary keys. By providing a dictionary value to each username, we may keep user data. We save each user's location, last name, and first name in the example. Iterating across users and accessing their data dictionaries yields this data. Let's study this Python code:

The included code creates a dictionary called "users" with two keys: 'aeinstein' and 'mcurie'. Dictionary keys correlate first and last names, localities, and other data. One for loop iterates through the "users" dictionary. This loop stores each key in "username" and the dictionary associated with each username in "user_info". The first print() statement outputs the username. 

The code retrieves the user_info variable's internal dictionary after print(). This internal dictionary has "first," "last," and "location" keys. The code creates a name and location for each person using each key and then summarizes their information.

Summary

Python dictionaries, which use key-value pairs, are powerful and versatile data structures. Dictionaries differ from lists by enabling keys of any data type to correspond to specified values, marked by braces{}. Their dynamic information storage syntax allows applicability in numerous programming settings.

Like lists, dictionaries offer looping and quick item access. Key-value associations use the colon(:) within braces to indicate data connections cleanly and effectively. The “dict()” method initializes an empty dictionary.

In real-world applications, dictionaries properly model things using key-value pairs. Dictionary functions like looping and accessing values highlight dictionaries' versatility and efficiency in organizing and handling varied data sets.

Dynamic dictionaries offer smooth key-value pair addition using square brackets and the assignments operator. Dictionary order is immaterial, unlike lists, where order is necessary for equality.

Dictionaries differ from lists in ordering criteria, highlighting their uniqueness. Despite KeyError when handling missing keys, dictionaries are flexible enough to update birthdate information with user input.

This chapter shows how Python dictionaries may organize varied data types and be powerful programming tools. Dictionary looping and layered structures for complicated data situations enhance understanding of these dynamic data structures.

INTRODUCING LIST IN PYTHON

Python Lists

Introduction

  • Introduction to Lists
  • Accessing Elements
  • List Operations
  • Modifying Lists
  • List Comprehensions
  • Iterating Over Lists
  • Copying Lists
  • Sorting and Reversing
  • List Membership Testing
  • Nested Lists
  • List Operations Efficiency
  • List as Stack and Queue

The fundamental Python data structure is presented in this chapter. Python creates a list as a fundamental data structure. We know how to build or initialize a list before working with its components. Whether we're working with millions or one, lists make it easier to store everything in one place. Due to their popularity and ease of use, some say Python's lists are its most powerful feature.

In contrast to arrays, Python lists are versatile. They can carry many data kinds and be scaled dynamically, making them easy to alter. 

What is a List?

A list is an ordered group. Python lists are defined with commas and square brackets '[]'. A list can contain numbers, strings, or other lists. Lists can organize and modify data well.

No link between list items is required; we can include anything. Lists usually contain several items, thus use the plural form of names, numbers, and letters.

Below is an example of a list in which we define a list in Python that contains various elements.

The above code list in the Python example declares a list called "my_list" and adds entries of various data types. Another list is stored within this list. Strings, integers, floating-point numbers, and other collections make up the "my_list" collection. You can access list components by index, and the items stay in order owing to the lists' ordered sequence.

Add, delete, and edit list items, among other things. Python lists include several built-in functions and techniques for its use as a powerful data structure.

Real-World Example of Python Lists Usage

For an enhanced understanding of Python Lists, let's pretend we're shop managers who want to utilize them to keep track of the things we have in stock. In this scenario, we'd use Python lists to do just that.

The first step is to make a list called "inventory" in Python to hold all of the products. The list items stand in for products, and each one has details like name, price, quantity on hand, and category.

inventory = [

    {"name": "Apples", "price": 1.99, "quantity": 50, "category": "Fruits"},

    {"name": "Milk", "price": 2.49, "quantity": 20, "category": "Dairy"},

    {"name": "Bread", "price": 1.49, "quantity": 30, "category": "Bakery"},

    # Additional products can be added similarly

]

We can then perform various operations using Python list methods. For example, to add a new product to the inventory we write the below code:

new_product = {"name": "Eggs", "price": 2.99, "quantity": 40, "category": "Dairy"}

inventory.append(new_product)

To update the quantity of a specific product we write the following code:

for product in inventory:

    if product["name"] == "Apples":

        product["quantity"] += 10  # Increase the quantity by 10

To display all products in a specific category, such as “Fruits”, we write below code:

fruits = [product["name"] for product in inventory if product["category"] == "Fruits"]

print("Fruits in inventory:", fruits)

Python lists facilitate improved inventory control and management by enabling us to easily add, change, and retrieve product information as required, which in turn helps us efficiently manage our store's inventory.

Lists are mutable

The code above declares and fills "my_list" with various data types. Other lists are in this list. The "my_list" collection comprises strings, integers, floating-point values, and more. Because lists are ordered, you can access list components by index and keep them in order.

You may add, delete, and update list items. One of Python's most powerful data structures, lists have several built-in methods and functions.

In the above code, we can see that we reassigned the zero-index value with 1. With the help of square brackets and assignment operators.

Accessing Elements in a List

Python lists are ordered collections, so you may retrieve any item by index or position. The list name must be entered first. Insert the item's index in square brackets. Use this method to remove entries from the list. The code for accessing a list entry comes next:

This code accesses the first item of the 'body_parts' list by surrounding its index value in square brackets. We use '0' instead of 1 in the square bracket to get the first item of a list since Python list index values start with 0.

Additionally, string methods from the previous blog may be applied to any list element. To arrange the 'head' syntax, we may use title(). Using code to analyze:

The preceding code shows the output in title case with the first character capitalized using title(). Otherwise, this code outputs the same as before.

Since a list's index starts at 0, we may use the square bracket notation to access the following entries by passing 1 and so on. We may extract the element by subtracting one from its list position. Take it apart using codes.

As seen above, the head is at index 0, therefore supplying 1 as the position argument prints "hand" instead of "head." Similarly, passing 3 as position prints the last item. To print the last entry in the list without knowing its index, we can pass -1 inside square brackets. For example, we may provide -2 within square brackets to print the second-to-last entry of the list, and so on. I've put the code below for convenience.

Using Individual Values from a list

Use or access any list value like any other variable. Use list concatenation to construct an output message with one or more list components.


Code

In the above code, we can see that for the message variable, we use a string and then concatenate the list’s first element to it, to complete the message and then print it.

Adding and Removing Elements

Many computer languages use arrays, but adding things is difficult. However, Python's list simplifies object addition and removal.


Appending Elements to the End of a List

The list append method adds a new item to the end of a list. The append function adds a new item to a list. We can test this using an example:


Code

As demonstrated in the code, we added a new element to the list and placed it at the end using Python append to list.

The append() method makes it easy to build lists dynamically. We can build lists from the beginning with the help of the append() method because with this method we make a dynamic list whose size we can adjust according to our needs. Let's look at this process with the help of an empty list and adding elements one by one to it.

Extend Method
We use extend in Python when we need to add multiple elements at the end of the list. It is similar to the append Python method but in append-only add one element it can add multiple elements. It can also take another iterable (like a tuple, list, or string) as an argument and add each element from that iterable to the end of the list on which it is called. The extend method is very useful when we want to combine the contents of two lists or add many elements from another source to an existing list.
Using the enumerate Python method we can iterate over lists while we can track both the index and the corresponding value of each element. The enumerate method is mainly used with a for loop. List comprehension Python offers a concise and efficient way to create lists based on existing iterables.

Inserting Elements into a List

We may also use insert() to add a new element to a list point. Here, we instruct the system where to insert the new element in the index. We may analyze the code for clarity:

The following code snippet expands the list by introducing an ID 5 entry at index 2. The insert strategy helped us succeed. Insert takes two arguments. The new element and its location are represented by these properties.

Removing Elements from a list

We may frequently discover a cause to delete an element or item from a list using one of several methods; leaving it in the list would waste space and processing time. The next section examines these methods.

Removing an Item Using the del Statement

If we know which element we want to delete and its position, we can do it using the del statement. Let’s look at this using the code:

We can see in the above code we remove the zero-index value, from the list using the del statement, in this we need to pass the index value as an argument.

Removing an Item Using the pop() Method

Another option for removing items from a list is to use the pop() method. The final item in the list gets removed, but we are still able to interact with it afterward. Let's look at the code to better understand it.

In the above code, we can see that we remove the last element from the odd_number list using the pop() method and also store that popped item in another variable for future use.

Popping Items from any Position in a list

The pop() method allows us to delete an item from the list by enclosing its position or index value in brackets. How about we look at this with an example:

In the above code, we can see that we pass an argument which is the index value of the element inside the bracket of the pop method. This index value tells the pop method which element we want to remove from the list.

Removing an Item by Value

We can use remove() to delete an item or element if we don't know its location or index value in the list. We provide a value into this function in remove() brackets to delete it. Let's look at the code example to understand.

In the above code, we can see that the remove() method works with the value of the list, as we pass 10 inside the remove method bracket it removes the 10 from the even_number list.

Note: - The remove() function will only delete the first occurrence of the value we supply when we use it. If there's a possibility the value will appear more than once, a loop must be used to determine if it has been removed from the list.

Sorting a list Permanently with the sort() Method

Sorting Python list items is often important, and sort() makes it easy. Code example to help you understand: The automobiles list contains car manufacturers in whatever order you like. This list may be sorted alphabetically using sort().

In the above code, we can see that all the car brands are sorted in alphabetical order.

Sort() may also sort the list from bottom to top with the "reverse=True" option. The code for sorting the list from most to least important is below.


Note: Each above method sorts the list permanently means if we print the list again then they will print the sorted list, not the initial list that we created.

Sorting a List Temporarily with the sorted() Function

In the previous code, sort() permanently sorts the list, which isn't always desirable. Sometimes we just need a temporary sort to revert to the original list after our actions. This is achievable using sorted(). We can sort the list without affecting its order using sorted(). Seeing the Python code will help us understand.

The preceding code shows that the sorted function only sorts the list briefly.

The sorted function preserved the list's order. Use reverse=True with sorted() to display the list in reverse alphabetical order. The reverse=True option is passed inside the sorted bracket after the list to be sorted and a comma.

Printing a List in Reverse Order

The reverse() method reverses a list. We can reverse a list's order using the reverse method. This flips the list, placing the last item at the top and the first at the bottom. Seeing the Python code will help us understand.

Code snippet prints list in opposite order using reverse(). If we print the cars again in another portion of the program, they will be printed in reverse order. Because it permanently changes the list order.

Reversing the list once again restores its order, making it easy to restore.

Finding the Length of a List

The len() function makes counting list entries straightforward. It's also called list length. The length will be 6 feet, like the cars above. Use Python to check if.

In the above code, we can see that the length of the prints is the total number of elements/items present in the list. Which is 6 in the above case.

Note: Python counts the items in a list starting at one, so we shouldn't run into any off-by-one issues (i.e., removing one from the total count that is n-1) when determining the length of a list.

Getting Sublists with Slices

We can see that picking one item from a list is easy. Slice lets us remove multiple values from a list and create a new one. Similar to indexing, square brackets are used to get several elements from a list or sublist from a bigger list, but instead of a colon, two numbers slice the list. Our first topic is list indexing and slicing.

  • Cars[2] is a list with an index (one integer).
  • Cars[1:4] is a list with a slice (two integers).

Initial numbers in Slicing specify the list or index the procedure should start at. The second integer is an end-of-slice index. A slice's second index is empty. A 1:4 slice ratio means cutting starts at index 1 and goes to index 3, bypassing index 4. Each slice has a unique list value.

The following code snippet slices the index from start to finish to output the complete list. The third line, or second print, prints item values 2–4 from index 1–4. Since the list index starts at 0, the 4 index implies 5 items but not the last. In the last print, we send negative 1 as the second input, the last list item. For instance, passing -2 in the second element signifies the second last item in the list, and so on. Starting from the beginning, this prints all items except the final.

We can start the index with 0 at the beginning of the list, or the value before the colon. We can leave the second index value empty to include entries at the end using the list length. This slices to the end of the list. Python programming can help us comprehend them.

The above code shows that the list is displayed from the beginning because the first index value was not specified. Since we removed the second set of index values from the second list, it will print out the entire second set from first to last. Omitting the first and second index values from the third list prints the complete list.

Looping Through a Slice
If we want to go through each element/item of the sub-list then we can also use for loop in the sub-list to iterate over all the items of the sub-list. Let’s look at the code example of this.

In the code above, we created a list called players and saved the player's name. The second line's players list is iterated using a for loop. We establish a sub-list to include only the third player in the new list. 

List Concatenation and List Replication

The list can be copied or joined. The plus sign (or operator) may concatenate two lists, just like we combine two strings to make a new string. The * operator can duplicate two strings and lists with an integer value for list replication. For clarity, let's use Python code.

In the code sample above, we connect two lists—integers and strings—at the start. Multiplying a list by 3 displays the same item three times. We printed a spam list after joining it with another list using the plus symbol (+).

Changing Values in a List with Indexes

If we surround the list in square brackets and use the index values to determine which value to change, we can use the assignment operator to change any item's value. For instance: "spam[1] = 'Rohit'." The code produces an index-based spam list. It retrieves index 1 and assigns a new value using the assignment operator. 


Avoiding Index Errors When Working with Lists

The most common list error is trying to access an index that isn't in the list. Let's say we have a 4-item list with an index of 0, thus the final item's index is 3. By mistakenly typing 4 in the square bracket, we want to access it. Let's look at Python code to understand.

In the code, index errors indicate that the Python interpreter cannot find the 5 items or 4 index values in the list because it is too big.

In most circumstances, passing -1 in square brackets with the list name prints the last value. Only when printing the last element from an empty list does an error occur.

It also shows out-of-range errors or index errors.

Note: In case an index error arises and troubleshooting becomes challenging, consider printing the list or its length. Sometimes, the actual contents of the list might differ from our expectations, especially if it's been dynamically altered during program execution. Observing the list's actual content or its precise length can aid in identifying and resolving such logical errors effectively.

Traversing a List
Working with Lists (While loop)

When we start coding, we typically create numerous variables with the same data, which is non-functional. To remember our friend's name, we can:

We've seen that this data-storing method isn't code. The program cannot manage more friends than the default variables, regardless of name or number changes. This organization often produces identical or duplicate code. Examining the code that creates the outcome shows duplicates and similarities.

The vast number of variables initialized and duplicate code makes the above code bad programming. Using the list, we can overcome this.

Using one variable with a list value instead of numerous recurring variables is more efficient. Look at an improved code snippet from previously. This updated version uses a single list to input infinite buddy names. 

The code and results show that this way is better than the previous one since we can add limitless friend names without adding variables or lines of code.

Using the Loops with Lists

Loops—usually the "for" loop—are needed to extract elements from a list one by one. The "for" loop executes the code block for each item in a list or equivalent data. The list operator syntax is the same as the string "for" loop.

for i in list_name:
print(i)
Let’s look at the code for better understanding.

The following code sample creates a list called "number_list" and prints each item using a for loop.

A for loop with range(len(list_name)) is a typical approach to exploring a list's indices in Python. Python code sample demonstrating this strategy:

The following for loop iterates across list indexes using range() and len() after initializing a list. Finally, the print command displays index numbers and list elements.

The in and the not-in Operators

Python's "in" and "not in" operators checklist items for presence. These operators verify if a list has a value. The "in" operator returns True if the value is in the list, and False otherwise. If the item is not in the list, the "not in" operator returns True; otherwise, False. List searches and membership verification are easier with these actions.

Let’s look at Python code for a better understanding and how it works.

The code above returns True if the value is in the list and False otherwise. The "in" operator checks if a value is in the list. Using the "not in" operator to confirm the value isn't in the list doesn't work; it's False.

Look at this example again. We verify if a name is in the list once the user enters it. A message appears if it's not. We publish the name if so.

Create and initialize a list named "names" with a list of names using the following code. Then, it verifies if the name is on the list when the user inputs it. If not, it writes that Chota Bheem's main character doesn't have that name. If so, it prints that Chota Bheem's primary character is named.

The Multiple Assignment Trick

Lists let us assign several variables with list values in a single line of code. Reading Python code will help us understand.

Here, we build a list called cat and assign variables to each item using index values. However, this method is inefficient and wasteful. We can write one line to do this instead of many lines of code. See how we can. 

We build a list called cat and assign variables to each item using index values. However, this method is ineffectual and unneeded. We can achieve this with one line of code instead of several. Explore how we can.

Above we can see that if we pass more numbers as a variable compared to the list’s item then it will generate ValueError.

Finding a Value in a List with the index() Method

The index() function returns a list item's index. Finding an item not in the list will throw a ValueError. Two Python code examples show the two outcomes: success and ValueError.

In the above code, we can see that we pass the ‘black’ argument inside the index() method and it prints the index value 1 as a correct result. 

In the above code, we can see that we pass an argument inside the index() method that is not available in the list as a result Python produces a Value Error.

Simple Statistics with a List of Numbers

Some Python function lists demand integers for all list items. Using the functions, you may find the minimum, maximum, and total of a set of integers. 


In the above code, we can see that we created a list called number which has only in it, and after its initialization, we print the minimum, maximum, and sum values of the list.

List Comprehensions

With one line of code, list comprehension lets you generate and iterate through items. This sophisticated capability automatically adds new items to the list. Despite its strength, newcomers should avoid using it until they understand Python because it's challenging. It's important to understand list comprehensions while reviewing other people's code.

As we can see in the code snippet above, we create a list named square and initialize it using list comprehensions. Specifically, we use a for loop to traverse from 1 to 10, square each element, and then put it in squares.

Copying List

Creating a new list with all items from an old one is commonly desired. To duplicate a complete list, create a new list with the desired name and use the assignment operator. The right of the operator is square brackets. In these brackets, a colon is an argument. Make sure both sides of the colon are empty to add all entries from the previous list to the new one. Looking at the code may help.

The code line creates a "my_foods" list for food. The second line creates a "friend_food" list. Slicing and indexing allow us to take a subset of "my_foods" and preserve it in the "friend_food" list, duplicating its contents. This duplicates "my_foods" in "friend_food".

They make separate lists to prove independence. I suggest using the append function to add a new, different item to both and printing the list again.

The code shows that we started two lists—one that replicates all things to another and another that does the same—before adding two unique items to each and printing them. Each list has a different last element, thus they are separate and stored in different memory locations.

The friends_foods list will not include a duplicate of my_foods unless the assignment operator is in square brackets. This code assigns "friend_food" to the same list object as "my_foods". Python's "=" assignment method adds the new "friend_food" variable to the "my_foods" list. The "my_foods" and "friend_food" variables now share the same list and contents. Since "my_foods" and "friend_food" refer to the same list, altering one will affect the other. Adding, deleting, or changing "my_foods" changes the "friends_food" list. We can check this with a Python code example. 

The preceding code shows that we started a list called "my_foods" and then used the assignment operator to create a second variable called "friends_food" that references it. We produced two lists, "my foods" and "friends food," after adding an item to the former. The newly inserted item appears in both printed lists. We added another item to "friend_foods" and printed both lists again. This time, both lists have the new item.

Tuples

Lists are great for managing dynamic data, whose number and kind change over time and according to our needs. We often need static lists for online account administration or game character storage. However, we sometimes require an immutable list. Tuple in Python enables us to create immutable lists, which is useful in certain scenarios. Python immutable values cannot be changed.

Unlike lists, tuples are created with parenthesis instead of square brackets. After generation, we may obtain each element using its index, just like a list. A Python code tuple example will help illustrate this.

The code above forms a tuple using parenthesis and retrieves its components with square brackets, like a list.

Tuples are immutable, therefore changing their values fails. What error occurs when we edit a tuple's value?

In the above code, we can see that if we try to change the value of a tuple it gives TypeError, and also gives a message 
We can also define a tuple with a comma-separated list of values. Let’s look at this with the help of Python code.

The code sample defines a tuple as a comma-separated list. Printing the type of a tuple verifies its construction. Classy, as expected. Additionally, its components may be obtained by index.

As said, parentheses are common but not essential for tuples. A tuple with one element requires one last comma, as seen in the Python code below:

A single value inside the parentheses is not a tuple it can be another data type like string, integer, etc. Below we can see its example code.

You may also build a tuple using the built-in 'tuple()' method. Invoked without parameters returns an empty tuple. It will convert a string or other sequence into a tuple, with each component becoming an element of the new structure. We can then use Python to inspect them.

Initialization generates an empty tuple. The second tuple is built using tuple(). Remember that the tuple() method only accepts one parameter and prints the pass text in tuple format.

Using square brackets, we can slice a tuple like a list. Examine the Python code to understand.

In the above code, we can see that we slice the index from 1 to 3 of the tuple (note: tuple also does not include the upper bound of the index), and also if we try to update or modify the element of the tuple we get an error, called TypeError.

Tuple Assignment

In programming, it is very common to swap two variables. In traditional assignments, we have to use a temporary variable. For example, let’s look at Python code for swapping two variables.

The code sample above declares "a" and "b" first, followed by "temp" as a temporary variable. After giving b to a, we give b the temporary value. We can observe that printing modified a and b.

We can do this very easily using tuple assignment let’s look at that using Python code.

The code sample has an expression tuple on the right and a variable tuple on the left. Right-hand tuple data is allocated to left-hand variables. Always analyze right-side phrases before assigning.

Note: it is called tuple assignment but if we print the type of variable, it will show integers in this case and also respective for their types in other cases.

Looping Through All Values in a Tuple

As with lists, we may use a for loop to go through tuples' values because they are immutable. Let's look at Python code to understand.

In the above code, we can see that we iterate over a Python tuple using a for loop.

Writing over a Tuple

Since Python tuples are immutable, their components cannot be modified. But a tuple-holding variable can change value. Redefining a tuple updates its contents. To illustrate, let's look at a Python code sample.

In the above code, we see that first we declare a tuple t and print its element one by one using for loop, and in the second section of the code we redefine the tuple t with all new elements and print its element one by one using for loop.

Summary

Python lists may hold several data types and change size. They are essential for data management and manipulation, enabling flexibility not available in conventional programming languages. Square bracketed lists support integers, strings, and other lists. Indexing and retrieving items is straightforward using the ordered sequence.

List operations include adding, deleting, and changing. Mutable lists allow developers to alter element values using square brackets. Python's zero-based indexing makes list items easy to retrieve. List items support string methods.

Appending components using append() simplifies incremental list creation. The insert() function inserts items to particular list locations. By index, the del statement deletes an element. Pop() removes the final element, whereas remove() deletes the first value. Sort() permanently sorts a list, while sorted() temporarily sorts it without changing the order. The reverse() method reverses items and len() returns the list length.

Slices and indexes find sublists or individual entries, whereas for loops iterate. Concatenation and replication use + and * operators. Assignment and index modify list items. Index errors must be handled, and -1 obtains the final entry.

Making lists instead of variables improves code performance. List manipulation is optimized via loops, operators, and list-specific functions.

Tuple collections are ordered and immutable. Changing values in parenthesis causes TypeErrors. Tuple assignment makes variable switching efficient. To modify tuple content, assign a new value and loop over them like lists.

Python tuples are ordered, immutable collections for maintaining unchangeable data. This chapter optimizes code performance and flexibility by switching from variables to lists. Python programming requires knowledge of list and tuple operations.

Featured Post

ASSOCIATION RULE IN MACHINE LEARNING/PYTHON/ARTIFICIAL INTELLIGENCE

Association rule   Rule Evaluation Metrics Applications of Association Rule Learning Advantages of Association Rule Mining Disadvantages of ...

Popular