One place for hosting & domains

      Python

      Converting Data Types in Python


      Python is a dynamically typed language, so programmers might not always consider the type of each variable they create. However, the type of a variable is often important, and it might be necessary to convert it to another data type. This guide explains how typecasting works and illustrates how to convert data types in Python. It covers several common examples, such as how to convert an integer to a string.

      Convert Data Types in Python: An Introduction

      Python, like most programming languages, supports a wide range of data types. Python is considered a strongly typed language, so each variable always has a type. The type of a variable governs the data it can represent and constrains how it can be used. Some common Python data types include integer, float, string, list, dictionary, and set. In Python, an object’s type defines its methods and the set of operations it supports. For instance, it is possible to calculate the exponent of an integer, but not of a string. For more information about Python data types, see the
      documentation for standard types
      and
      advanced types
      .

      In addition to being strongly typed, Python is also dynamically typed. This means the type of a variable is determined only at run time. The Python interpreter does not perform any type checking in advance. In addition, the type of a Python variable can change over the course of a program. Statically typed languages such as C++ do not permit this.

      It is possible to change the data type of a variable in Python through datatype conversion. Datatype conversion allows variables to be used more effectively within the program. For example, an integer can be converted into a string, allowing it to be appended to another string. There are two different methods used to convert data types in Python.

      Implicit type conversion: Python automatically performs implicit type conversion without user intervention. It can elevate a lower-order data type, such as an integer, to a higher-order type like a float. Python can initiate this conversion because any integer can be unambiguously represented as a float. There is no chance of misinterpreting the intent of this operation. Implicit conversion avoids the loss of any data and is highly convenient. However, it does not work in all cases.

      Explicit type conversion: This is also known as typecasting. An explicit conversion must be performed manually using one of Python’s built-in methods. This is necessary when the conversion is not straightforward and the intent of the operation is not clear. Some explicit type conversions can cause data loss.

      The Python type function is used to determine the type of the data. In this example, x is of type int, while y is of type float.

      x = 10
      y = 10.01
      print(type(x))
      
      <class 'int'>
      print(type(y))
      
      <class 'float'>

      Before You Begin

      Ensure Python is already installed on your machine and you understand how to launch and use the Python programming environment. To run Python on Ubuntu, use the command python3. For more information regarding how to use Python, see the
      Linode guide to Python
      .

      Converting Integers and Floats in Python

      Both floats and integers represent numerical values. A float number has a decimal point, while an integer does not. A float can more precisely represent a number, but integers make more sense when dealing with countable values. An integer can always be represented as a float, but most floats cannot be represented as integers without a loss of precision.

      This process of converting between integers and floats is relatively straightforward, because both types represent numerical data. Additional methods exist to convert integers to other formats, such as hexadecimal strings. The following examples illustrate the main methods used to convert numerical data types in Python.

      Converting Integers to Floats

      The built-in Python function float() converts an integer to a float. It accepts a single integer and returns its float equivalent in the proper format, complete with a decimal point.

      x = 10
      z = float(x)
      print("z is", z, "and is of type", type(z))
      
      z is 10.0 and is of type <class 'float'>

      Python can automatically elevate an integer to a float using implicit type conversion. Therefore, if the result of float(x) is reassigned to x, x changes type and becomes a float.

      x = 10
      x = float(x)
      print("x is", x, "and is of type", type(x))
      
      x is 10.0 and is of type <class 'float'>

      When an integer and a float are added or multiplied together, the result is a float.

      x = 10
      y = 5.2
      z = x + y
      print("z is", z, "and is of type", type(z))
      
      z is 15.2 and is of type <class 'float'>

      This occurs even if the answer can be perfectly represented as an integer. In this example, the result is 52, but it is represented as a float containing the value 52.0.

      z = x * y
      print("z is", z, "and is of type", type(z))
      
      z is 52.0 and is of type <class 'float'>

      As of Python 3, when two integers are divided, the result is a float. The numerator and denominator are both internally pre-converted to floats before the operation. This means the result is a float even if the modulus is zero.

      Note

      Python 2 returns an integer in this case.

      x = 6
      y = 3
      z = x / y
      print("z is", z, "and is of type", type(z))
      
      z is 2.0 and is of type <class 'float'>

      Note

      The closely-related hex() and oct() methods can convert an integer to its hexadecimal or octal string equivalent.

      Converting Floats to Integers

      To convert a float data type to an integer in Python, use the int() function. This function removes the fractional component of the float, also known as the
      mantissa
      , during the conversion.

      x = 50.8
      x = int(x)
      print("x is", x, "and is of type", type(x))
      
      x is 50 and is of type <class 'int'>

      This conversion leads to some data loss. The truncated portion is not recovered even if the variable is converted back to a float.

      x = float(x)
      print("x is", x, "and is of type", type(x))
      
      x is 50.0 and is of type <class 'float'>

      To convert a float to the nearest integer, use the round() function instead.

      x = 50.8
      x = round(x)
      print("x is", x, "and is of type", type(x))
      
      x is 51 and is of type <class 'int'>

      Note

      Some information is permanently lost whenever a float is converted to an integer. This can have drastic effects on the accuracy of future calculations. Ensure you understand the implications of this data loss within the context of your program before proceeding. When in doubt, create a new variable to store the converted value.

      Converting Strings in Python

      A Python string consists of an immutable sequence of Unicode characters, and is represented internally as an array. The individual characters in a string can be accessed using string indexing, which is similar to
      how list items are accessed
      . Python string indexing is zero-based, so the index [1] refers to the second character in the string. Python provides a number of built-in methods for use in string processing and manipulation.

      Integers can be converted to strings and vice versa. Strings can also be converted to complex data types including lists, sets, and tuples. For more information on strings, see the
      Python documentation
      .

      Converting Int to String in Python

      Adding an integer and a string is more complicated than adding two numbers. The integer could potentially be treated as a string, but the string could also be converted to an integer. For instance, should the operation 14 + "12" result in the string 1412 or the numerical value 26? To resolve any confusion, a Python string and integer cannot be added together or concatenated. Both entities must have the same type. Either the integer must be changed to a string, or the string must be converted to an integer. In the following example, adding a string to an integer results in an error.

      x = 12
      y = "23"
      z = x + y
      
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      TypeError: unsupported operand type(s) for +: 'int' and 'str'

      To convert an int to a string in Python, use the built-in function str(). When an integer is passed to the str() function, it is converted to a text representation of the number. The following example uses the str() function to perform type conversion on the integer variable x, allowing it to be concatenated to another string. The end result of the operation is another string.

      x = 12
      y = "23"
      z = str(x) + y
      print("z is", z, "and is of type", type(z))
      
      z is 1223 and is of type <class 'str'>

      This approach is frequently used to print text consisting of both strings and numbers. The numerical component is converted to a string when it is passed to the print() function.

      print(str(x) + y)
      
      1223

      The str() function can also be used to convert other data types, such as a float, to strings. This function accepts a floating point number and converts it to a string, with the decimal point and fractional component still intact.

      Convert String to Int in Python

      Mathematical operations cannot be performed on string objects. They must be converted to numbers first. Fortunately, Python’s built-in int() function is very flexible and can convert several data types to integers. This function accepts any string that can be converted to an integer, and returns an integer representation. If the string cannot represent an integer, Python throws an error. The following example demonstrates how to convert a string to an int in Python.

      x = "101"
      z = int(x)
      print("z is", z, "and is of type", type(z))
      
      z is 101 and is of type <class 'int'>

      This function can be used to add a string representation of an integer to an actual integer. This code sample converts the string to an integer, allowing the two numbers to be added together. This contrasts with the earlier example, which used str() to perform a string concatenation.

      x = 12
      y = "23"
      z = x + int(y)
      print("z is", z, "and is of type", type(z))
      
      z is 35 and is of type <class 'int'>

      When passing a string to int(), it is possible to add an optional argument indicating the base of the number. For instance, int("101", 2) indicates the binary string 101 is equivalent to 5 in decimal notation. It is not the integer 101. If a base is not provided, Python assumes it is a base-10 decimal number.

      x = "101"
      z = int(x,2)
      print("z is", z, "and is of type", type(z))
      
      z is 5 and is of type <class 'int'>

      Strings can also be converted to floats using the float() function. Python cannot automatically convert a float-like string to an integer. This function must be used if the string has a decimal point, and the string must represent a float.

      x = "10.00"
      z = float(x)
      print("z is", z, "and is of type", type(z))
      
      z is 10.0 and is of type <class 'float'>

      Note

      Do not confuse the int() function with ord(). ord() converts a character to its ASCII integer representation. This function uses the
      character to ASCII conversion table
      to determine the ASCII values.

      Converting Strings to Lists

      In Python, a list is an ordered array of objects. The items are mutable, so they can be changed. Items can be added, removed, or modified. Lists also have a large collection of built-in methods, providing advanced processing features. A list is enclosed in square brackets [ ] with commas separating the items. An example of a list is ['aa', 'bb', 'cc'].

      Lists and strings are conceptually very similar. Both are ordered sequences, and the individual items are accessed the same way. This makes it easy to convert a string to a list. The first letter in the string becomes item [0] in the list. The second letter becomes the second list item, and so on.

      Note

      The elements of a list can be strings or numbers, or even compound objects. However, strings can only contain a sequence of Unicode characters.
      Lists can also be converted to strings in Python
      , but the steps are more complicated.

      To convert a Python string to a list, use the list() function and provide the string as input. This results in a list containing the characters in the original string, formatted in list notation.

      x = "test"
      z = list(x)
      print("z is", z, "and is of type", type(z))
      
      z is ['t', 'e', 's', 't'] and is of type <class 'list'>

      Converting Strings to Tuples

      Strings are also easily converted to tuples. A Python tuple is almost the same as a list, except it is immutable. This means it cannot be changed after it is created. A tuple is always enclosed by parentheses ( ). It is sometimes a more efficient data structure for string processing because it includes more built-in functions.

      To convert a string to a tuple, use the tuple() function. The characters in the string become the ordered elements of the tuple.

      x = "test"
      z = tuple(x)
      print("z is", z, "and is of type", type(z))
      
      z is ('t', 'e', 's', 't') and is of type <class 'tuple'>

      Note

      Although it is relatively uncommon, a string can also be converted to a set. A set is an unordered collection of unique elements. Use the function set() and provide the string as a parameter.

      To learn more about Python tuples, see our guide
      An Introduction to Python Tuples
      .

      Conclusion

      Although Python is a dynamically-typed language, type conversion is still very important. Python frequently uses implicit type conversion to elevate an integer to a float, making certain operations easier. However, developers often have to use explicit type conversion, changing a type using Python’s built-in functions.

      This guide explains how to convert data types in Python. It is possible to convert a string to an integer in Python using the int() function, while the str() function converts an integer to a string. Integers can be converted to floats using float(), and floats can be changed to integers, although this can cause data loss. Other functions allow strings to be converted to array formats such as lists, tuples, and sets.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link

      Python Arrays: What They Are and How to Use Them


      Python arrays provide an effective way to store multiple values of the same type in a single variable. In this tutorial, you learn what Python arrays are and how to use them, and the difference between Python lists and arrays. You also learn how to loop through an array, add and remove elements from an array, and how to combine the values stored in different arrays.

      What Are Arrays in Python?

      In Python, an array is an ordered collection of objects, all of the same type. These characteristics give arrays two main benefits. First, items in an array can be consistently identified by their index, or location, within the array. Second, items in an array are assured to be of the same type.

      When creating an array in Python, you must indicate the type of data to be stored. The available types are indicated using codes, which consist of the following:

      Type CodeC TypePython TypeMin. Bytes
      ‘b’signed charint1
      ‘B’unsigned charint1
      ‘u’wchar_tUnicode character2
      ‘h’signed shortint2
      ‘H’unsigned shortint2
      ‘i’signed intint2
      ‘I’unsigned intint2
      ‘l’signed longint4
      ‘L’unsigned longint4
      ‘q’signed long longint8
      ‘Q’unsigned long longint8
      ‘f’floatfloat4
      ’d’doublefloat8

      Generally, though, for arrays containing numbers, you can focus on using just two of the available codes. Use the i code for arrays containing integers. Use the d code for arrays containing floating point numbers.

      You can see an example showing how to use a code to initiate an array at the beginning of the
      How to Use Arrays in Python
      section of this guide.

      Python Arrays vs. Lists

      Often, people talking about arrays in Python are actually referring to
      Python lists
      . While lists and arrays share some similarities in Python, they are two distinct types of collections.

      The main difference between lists and arrays is that arrays constrain the object type it can store. Lists do not give you a way to limit the types of objects they contain. When using an array, you can be sure that it only contains the type that was specified upon creation.

      A single Python list can simultaneously store integers, strings, and dictionaries. You can even add more elements of still other types to an existing list. By contrast, elements in a Python array can only be of one type. An array of integers can only contain integers and can only have other integers added to it.

      Aside from this difference, however, you can generally navigate and modify arrays and lists in the same way. All of the operations detailed below for arrays, except for the array() function itself, can be applied to lists as well.

      How to Use Arrays in Python

      The next few sections of this guide show you how to work with arrays in Python. Python has a wide variety of operations that can help you effectively make use of arrays. The sections below demonstrate the most common operations you might need to perform on arrays.

      All of the examples to follow work off of a simple integer array created using the following Python code:

      from array import *
      example_array = array("i", [2, 4, 6, 8])
      

      Note

      The
      array module
      is not loaded by default in Python. Instead, you need to import the module to start working with arrays.

      There are two ways you can interact with the contents of an array: either through Python’s indexing notation or through looping. Each of these is covered in the sections that follow.

      Python Array Indices and Slices

      The individual elements of an array can be accessed using indices. Array indices begin at 0. This means that the first element of an array is assigned an index of 0, and each subsequent element’s index progresses from there.

      So, to access the first, second, and third elements of the example_array, you use the following index notation:

      example_array[0]
      
      2
      example_array[1]
      
      4
      example_array[2]
      
      6

      You can also use negative numbers as indices. When you use a negative number as an index, Python counts backwards through the array, starting with -1 as the last item in the array. The following example accesses the last value stored in example_array:

      example_array[-1]
      
      8

      Python supports more advanced indexing through its slice notation. Slicing allows you to select a range of elements from an array.

      The syntax for slice notation is the following:

      [start:stop:step]
      

      start defines the first index of the range and stop defines the last. The step portion is optional. It is used to define how many elements to progress through while moving over the range start and stop range. By default, the value of set is 1.

      The next example slices the range from index 0 through index 3. It progresses through this range using 2 steps at a time, meaning it skips every other item:

      example_array[0:3:2]
      
      array('i', [2, 6])

      Python’s slice notation is a powerful tool that can be used to perform many more complicated operations than demonstrated in this guide. To see more examples with in-depth explanations, check out our guides
      How to Slice and Index Strings in Python
      and
      Python Lists and How to Use Them
      . While these guides do not deal directly with Python arrays, the concepts apply equally well.

      Looping Over Array Elements

      Python arrays can be iterated over using for loops. This provides a convenient way to take an action on each element in an array. Each loop yields a variable — item in the example — corresponding to an element in the array:

      for item in example_array:
          print(item)
      

      The output returns the value of every element in the array.

      2
      4
      6
      8

      Using the enumerate function, you simultaneously loop through the elements and their indices:

      for i, item in enumerate(test_array):
          print(str(i + 1) + ": " + str(item))
      

      The enumerate() function returns the count of the current iteration (stored in the i variable) and the value of the current iteration (stored in the item variable). Since array indexes begin at 0, the statement inside the loop adds 1 to the value of the i counter to calculate the current index.

      1: 2
      2: 4
      3: 6
      4: 8

      The output returns the index number of the current element in the array along with the value itself. The index and the value are separated by a : as indicated in the enumerate() function’s print statement.

      Modifying Python Arrays

      Python also provides ways of modifying the contents of an array, whether you need to add elements or remove them. There is even a way to combine multiple arrays. These next sections show you how to do all of these operations, working with the same example array as above.

      Add an Element to an Array

      Python arrays include two built-in methods for adding new elements. Which method you use depends on where within the array you want the new element to be added.

      Use the append() method to add a new element to the end of an array. The example below adds the integer 10 as a new element at the end of example_array:

      example_array.append(10)
      print(example_array)
      

      The array example_array now also contains the 10 integer.

      array('i', [2, 4, 6, 8, 10])

      Use the insert() method to add a new element to a specific position within an array. The method accepts two parameters; the first parameter is the index where the element should be inserted and the second is the element to insert into the array.

      The example below uses the insert() method to place the integer 7 in example_array index position 3.

      example_array.insert(3, 7)
      print(example_array)
      

      Printing the array confirms that it now contains integer 7 in index position 3:

      array('i', [2, 4, 6, 7, 8, 10])

      Remove an Element from an Array

      Python arrays include two built-in methods that you can use to remove elements from an array. The method you choose depends on whether you want to remove an element based on a given value or a given index.

      The remove() method takes as a parameter the value to remove from the array. In the following example, the remove() method removes integer 7 from example_array. This integer was added to the array in the previous section.

      example_array.remove(7)
      print(example_array)
      

      The output confirms that example_array no longer contains 7.

      array('i', [2, 4, 6, 8, 10])

      The pop() method, on the other hand, can be used to remove elements based on index. This next example uses the -1 index to remove the last element in the array, which was one of the elements added in the previous section:

      example_array.pop(-1)
      print(example_array)
      
      10
      array('i', [2, 4, 6, 8])

      The pop() method returns the value of the element that has been removed. This is why the output displays the integer 10. This is useful if, for example, you want to store the value of the removed element in a new variable.

      Combining Arrays

      Python arrays can be combined, or concatenated, using the + operator. There are other ways to go about combining arrays — using a loop, for instance. But the + operator provides the most convenient method if your goal is simply to join two or more arrays.

      In the example below, the example_array is combined with a new array, another_array, and stored in combined_array.

      example_array = array("i", [2, 4, 6, 8])
      another_array = array("i", [20, 40, 60, 80])
      combined_array = example_array + another_array
      print(combined_array)
      

      Printing combined_array confirms that it now contains all the values stored in the two concatenated arrays.

      array('i', [2, 4, 6, 8, 20, 40, 60, 80])

      Conclusion

      Python arrays are a collection type that can store multiple values. Each value can be accessed using index notation. While a Python array is similar to a list, it differs in that you can only store values of the same type in an array. Arrays also have built-in methods that help you add and remove elements. You can also combine two arrays using the + operator.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link

      What is the Python Priority Queue?


      In Python, queues are frequently used to process items using a first in first out (FIFO) strategy. However, it is often necessary to account for the priority of each item when determining processing order. A queue that retrieves and removes items based on their priority as well as their arrival time is called a
      priority queue
      . Prioritization can be complicated, but fortunately Python priority queues can be easily and efficiently implemented using a built-in module. This guide introduces the Python priority queue and explains how to implement it in Python 3.

      Queues in Python

      What is a Queue?

      A queue is a fundamental
      programming data structure
      . Data structures are used to organize, manage, and store data. They make programs easier to understand and write, and often faster and more reliable too.

      Conceptually, a queue represents data items as an ordered list. Items are removed from the list in the same order they arrived. Queues are a familiar concept in everyday life. Every time a group of people line up for something, they form a queue. For instance, a line of people at a bank or a coffee shop is a queue. The first person to arrive is at the front of the queue. They are the next person to be served. When a new customer arrives, they join the back of the queue.

      In computer terms, queues are serviced using push and pop operations. Items are pushed onto the queue and are popped from the queue when they are due to be processed. The pop operation typically removes the item from the queue. However, it is sometimes possible to peek at the entry located at the front of the queue without removing it.

      Python supports queues through its extensive libraries. Built-in classes and routines handle all regular processing. You only have to create a queue object and call the methods to add new items and remove the oldest entries. Queues are usually the best choice for activities including scheduling tasks and processing incoming requests.

      The following example illustrates how queues operate on actual data.

      • To start, items A, B, C, and D arrive in the presented order. All four items are added to the queue in the order they arrive.
      • At this point, an item is chosen for processing. Item A is selected and removed from the queue. It is chosen because it arrived first and is at the front of the queue.
      • Next, item E arrives. It is added to the back of the queue.
      • Two more items are selected and removed. Items B and C are retrieved because they occupy the first two positions of the queue.
      • There are now two items in the queue. Item D is at the front and would be the next scheduled item, followed by E. The next item to arrive would be added to the end of the queue, following E.

      Queues can be contrasted with stacks. A stack is also a list-based data structure, but it uses a last in first out (LIFO) scheme. The most recent item to arrive is always the next item to be selected. Stacks are less obvious in day-to-day life, but are used whenever efficiency is preferred over strict fairness. For instance, stacks are used to store and retrieve non-perishable supplies. New supplies are placed on top of older orders. When more stock is necessary, the top items are removed first. In programming, most compilers extensively use stacks. They are also the best choice for evaluating mathematical expressions, because of the importance of order of operations.

      What is a Heap?

      Queues are efficient in Python because they are implemented as heaps. A heap is a special type of tree-based data structure. Trees are hierarchical data structures containing a parent node, which is called the root. The root can have child nodes, and each child node can also have children. This allows trees to grow organically to multiple layers. Heaps are usually implemented as binary trees. In a binary tree, each node cannot have more than two children.

      The two types of heaps are max heaps and min heaps. In a max heap, the value stored in the parent node is greater than the value stored in any of its child nodes. A min heap works in the opposite manner. The parent node contains a smaller value than any of its children. This relationship holds for each node at every level of the heap. This means values get progressively smaller at each lower layer in a max heap, or greater in a min heap.

      Heaps are a very efficient method for manipulating ordered data. They are particularly useful for retrieving the item with the highest or lowest value. In general, the algorithms used on a heap have either a constant or a
      logarithmic time complexity
      . This is very good because algorithmic growth increases fairly slowly as the size of the data set increases. And, of course,
      constant-time algorithms
      do not increase at all.

      Note

      In computer science,
      Big O notation
      is used to describe how execution time increases with the size of the data set. Most heap operations have an O(log n) time complexity.

      Although heaps are useful for ordering and organizing data, they have a downside. They must be kept balanced. This means extra work is necessary whenever nodes are added or removed. Heaps are more efficient with relatively static data sets, but can still be used when nodes are frequently added and deleted.

      What is Priority Queueing?

      A basic FIFO queue is the easiest and simplest queue to use. It is sometimes referred to as a strict queue. In this case, the oldest item must always be removed first with no exceptions. At times, this limitation is too inflexible. However, it is possible to add prioritization to the queue structure. This allows an entry to jump to the front of the queue even though it was not the first to arrive.

      A priority queue follows basic queueing principles, but maintains multiple sub-queues for the different priority levels. It pre-sorts the set of entries based on their priorities. The highest-priority entries are always serviced first, even if lower-priority items arrived earlier. In practice, the internal implementation of a priority queue does not usually construct multiple lists. Instead, the priority is used to determine where to insert the new item. This means the front of the queue is always serviced first, but new items do not automatically enter the queue at the back. In fact, it is possible for a very high priority item to be placed at the front of the queue.

      Priority queues are useful in many real-life situations. For example, airlines enforce priority queuing when boarding an aircraft. Business class customers form the highest priority queue and are boarded first. One or more regular fare queues are prioritized next, followed by any standby or low fare passengers. If a business customer arrives after regular fare passengers are already boarding, they go to the front of the line. Priority queuing is also used for triage purposes at a hospital or for servicing maintenance requests.

      In computing situations, multi-threaded operating systems use priority queues. Higher priority tasks are allocated first before background tasks. For example, mouse clicks take precedence over rendering a web page. In network routers, control traffic and routing updates are handled first before user traffic.

      The Python Priority Queue Class

      In Python, it is possible to build your own priority queues using Python lists. However, it is better to use the built-in PriorityQueue class. This class supports all of the basic functions such as put and get in a very efficient manner. Python automatically inserts and removes entries based on their priority and maintains the internal structure of the queues.

      A Python priority queue always removes and returns the highest-priority item in the queue. If two items have the same priority, Python removes the item that arrived first. For a tuple having both priority and data fields, Python first compares the priority and then the data item.

      Note

      To avoid using the data field in the comparison, enclose the PriorityQueue class in a wrapper and override its default behavior. Consult the
      Python PriorityQueue class documentation
      for more details about this technique.

      Python’s implementation of the PriorityQueue class extends the Python heapq module, which is based on a binary heap design. It is very easy to retrieve and remove the highest-priority item from a binary heap. Insertions and deletions have a time complexity of O(log n) even when re-balancing activities are accounted for. This means the PriorityQueue class remains quite efficient even with large data sets. In a max heap implementation, the highest-priority item at the front of the queue is always immediately accessible at the top of the heap. Inserting an item into the queue is somewhat more complex, but can still be accomplished in logarithmic time.

      For more details about how Python internally implements its PriorityQueue class, see the
      Python documentation
      .

      Importing PriorityQueue

      The PriorityQueue class is part of the queue module. It is described in the
      Python queue documentation
      , and can be imported using the following command.

      from queue import PriorityQueue
      

      This allows the constructor and all the class methods to be directly accessed without prepending the name of the module. For example, a priority queue can be created using the following command.

      q = PriorityQueue()
      

      If you require other functions in the queue library, it is possible to import the entire package.

      import queue
      

      In this case, the name of the module must precede the PriorityQueue constructor. The following line creates the same priority queue the first example did.

      q = queue.PriorityQueue()
      

      How to Use the PriorityQueue Class

      The PriorityQueue class shares most of the same methods as the parent Queue class. The
      Python Queue Documentation
      provides detailed information on the class constructor and all of the methods.

      Developers can create a PriorityQueue object using the class constructor. At the same time, they can supply a parameter to set a maximum size for the queue. The following command creates a priority queue that can hold 100 objects.

      q = PriorityQueue(100)
      

      Note

      The examples in this section assume the PriorityQueue class has already been imported using from queue import PriorityQueue.

      The PriorityQueue interface is fairly straightforward to use. The following list describes the most important methods.

      • empty: This function returns True if the queue is empty and contains no items. Otherwise, it returns False. This function is often used to determine if more get operations are required to service the queue.
      • full: This function returns True if the queue has reached its maximum size and has no more space for additional entries. A queue can typically only reach full capacity if a size limit has been configured. Otherwise, the queue size is bounded only by available memory.
      • get: This removes and returns the highest priority item from the queue. Additional parameters can be supplied indicating whether Python should block waiting for an item and how long it must wait. The default for the block parameter is True, while timeout defaults to None. By default, a get request blocks waiting forever for the next item to arrive.
      • maxsize: This method returns the maximum size of the queue. If there is no maximum size, it returns 0.
      • put: This method adds an item with the specified priority to the priority queue. Developers can add either a single value to function as the priority, or a tuple in the form (priority_number, data). A Python tuple is an ordered and immutable list. Similarly to the get method, block and timeout parameters can be passed to the method. The defaults are True and None. If the queue is full, the put method blocks until it times out waiting for a slot to become available.
      • qsize: This method returns the number of items currently in the queue.

      Note

      Some of the PriorityQueue commands, including empty, full, and qsize can be subject to race conditions when multiple processes are used.

      A queue can be deleted using the del command.

      del q
      

      An Example of a Python Priority Queue

      The example in this section demonstrates how to implement a Python priority queue for airline passengers using the PriorityQueue class. It explains how to create a queue, how to add and remove new entries, and how to remove all remaining items from the queue.

      1. Import the PriorityQueue package from the queue module.

        from queue import PriorityQueue
        
      2. Create a Python PriorityQueue, assigning the variable q to the object.

        q = PriorityQueue()
        
      3. Create three passengers using the put method. Customer Smith is in the business class, which is class 2, while customer Jones is in first class, designated as priority 1. The customer Wilson is in “standby” class 4. Each item is entered as a tuple, containing the priority along with the name of the customer. The tuple is enclosed in parentheses and is the only parameter passed to the put() method.

        q.put((2, "Smith"))
        q.put((1, "Jones"))
        q.put((4, "Wilson"))
        
      4. Remove customer Jones, who is the highest priority customer from the queue. Even though Jones arrived after Smith, they have the highest priority because they are in class 1.

         next = q.get()
         print(next)
        
        (1, 'Jones')
      5. It is sometimes helpful to verify whether the queue is empty or if it is full. The empty method should return False because two entries still remain. In practice, the queue is of unlimited size, so full is False too.

         print(q.empty())
        
        False
         print(q.full())
        
        False
      6. Add customer Collins to the queue with “standard” class priority 3.

        q.put((3, "Collins"))
        
      7. Remove the next customer from the queue. This is customer Smith.

        print(q.get())
        
        (2, 'Smith')
      8. To remove all remaining entries from the priority queue, use a while loop. At the loop entrance, confirm whether the loop is empty or not. If the empty method returns false, then there are still entries remaining. In this scenario, the get method extracts the highest priority item from the queue. Collins has a higher priority and is popped from the queue before Wilson is.

        Note

        If get is used on an empty queue with default settings, it is blocked until an item is available. To avoid deadlocks, it is important to either set the block parameter to False or to first verify whether the queue still contains more items.

        while not q.empty():
            print(q.get())
        
        (3, 'Collins')
        (4, 'Wilson')
      9. At this point, the queue should be empty.

        print(q.empty())
        
        True

      These instructions can be combined together to form the program pri_queue.py.

      Caution

      Do not name this program queue.py. This would conflict with the actual queue module and hide the actual interface. This bug generates the error ImportError: cannot import name 'priorityQueue' from partially initialized module 'queue' at runtime.

      File: pri_queue.py
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      
      from queue import PriorityQueue
      q = PriorityQueue()
      
      q.put((2, "Smith"))
      q.put((1, "Jones"))
      q.put((4, "Wilson"))
      
      next = q.get()
      print(next)
      
      print(q.empty())
      print(q.full())
      
      q.put((3, "Collins"))
      print(q.get())
      
      while not q.empty():
           print(q.get())
      
      print(q.empty())

      You can run the file with the following command:

      python3 pri_queue.py
      

      Getting the Size of a Priority Queue in Python

      To get the size of a Python queue, use the qsize command. The following example demonstrates how to determine the size of any queue in Python.

      1. Similarly to the previous example, import the PriorityQueue class and create a PriorityQueue object.

        from queue import PriorityQueue
        q = PriorityQueue()
        
      2. Add a couple of items to the queue with different priorities using the put routine.

        q.put(3)
        q.put(20)
        
      3. Verify the size of the priority queue using Python’s qsize method.

        print(q.qsize())
        
        2
      4. Add a new item to the queue and confirm the queue size again. It has increased to 3.

        q.put(11)
        print(q.qsize())
        
        3
      5. Remove an item from the queue using the get command. The qsize routine confirms the queue size is back to 2.

        q.get()
        print(q.qsize())
        
        2

      Conclusion

      Python queues are an important data structure that processes a list of items in a FIFO manner. Although traditional queues follow a strict FIFO algorithm, Python priority queues are able to prioritize the list entries. This allows high priority entries to be processed before lower-priority items that arrived earlier.

      Python includes a priority queue implementation as part of its queue module. It manages priority queues using a heap data structure. In a max heap, the value of the parent node is greater than the value stored in any of its children. Heaps make it easy to access the highest-priority item, and even insertions are relatively efficient with a logarithmic time complexity. Python priority queues have a simple and easy-to-understand interface. Items can be inserted using put, and retrieved using get. For more information on Python queues, see the
      official Python queue documentation
      .

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link