Introducing Lists in Python

Introduction


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

To better understand the Python Lists let’s consider a real-world example in which Python lists are used to manage inventory in a retail store in which we are managers and we want to keep track of the products available in our inventory using Python lists.

Firstly, we create a Python list named ‘inventory’ to store the products. Each element of the list represents a product, and it contains information such as the product name, price, quantity available, 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)

In this way, Python lists help us to efficiently manage our store’s inventory, allowing us to add, update, and retrieve product information as needed, ultimately contributing to better inventory control and management.

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 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 for 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.

Comments

Popular posts from this blog

Python Introduction

Logistic Regression in Machine Learning/Python/Artificial Intelligence

Basic Python