Python Articles

Page 657 of 855

Python - Which is faster to initialize lists?

Nizamuddin Siddiqui
Nizamuddin Siddiqui
Updated on 25-Mar-2026 264 Views

Python offers multiple ways to initialize lists, but their performance varies significantly. Understanding which method is fastest helps write more efficient code. This article compares four common list initialization methods: for loops, while loops, list comprehensions, and the star operator. Performance Comparison of List Initialization Methods Let's benchmark four different approaches to initialize a list with 10, 000 zeros and measure their execution times − import time # Initialize lists to store execution times for_loop_times = [] while_loop_times = [] list_comp_times = [] star_operator_times = [] # Run 500 iterations for reliable averages for ...

Read More

Python - Ways to merge strings into list

Nizamuddin Siddiqui
Nizamuddin Siddiqui
Updated on 25-Mar-2026 278 Views

While developing an application, there are many scenarios when we need to operate on strings and convert them into mutable data structures like lists. Python provides several ways to merge string representations into a single list. Using ast.literal_eval() The ast.literal_eval() method safely evaluates string literals containing Python expressions. This is the recommended approach for converting string representations to lists ? import ast # Initialization of strings str1 = "'Python', 'for', 'fun'" str2 = "'vishesh', 'ved'" str3 = "'Programmer'" # Initialization of list result_list = [] # Extending into single list for x in ...

Read More

Python - Ways to iterate tuple list of lists

Nizamuddin Siddiqui
Nizamuddin Siddiqui
Updated on 25-Mar-2026 251 Views

Lists are fundamental containers in Python programming used in day-to-day development. When dealing with nested structures like tuple lists of lists, knowing different iteration methods becomes essential for efficient data manipulation. Using zip_longest() with List Comprehension The zip_longest() function from itertools allows iteration across multiple lists of different lengths, filling missing values with None ? # using itertools.zip_longest from itertools import zip_longest # initialising list of lists test_list = [ [('11'), ('12'), ('13')], [('21'), ('22'), ('23')], [('31'), ('32'), ('33')] ] # printing ...

Read More

Python - Ways to invert mapping of dictionary

Nizamuddin Siddiqui
Nizamuddin Siddiqui
Updated on 25-Mar-2026 427 Views

Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. Inverting a dictionary means swapping keys and values, so the original values become the new keys and vice versa. Using Dictionary Comprehension The most Pythonic way to invert a dictionary is using dictionary comprehension ? # initialising dictionary ini_dict = {101: "vishesh", 201: "laptop"} # print initial dictionary print("initial dictionary:", ini_dict) # inverse mapping using dict comprehension inv_dict = {v: k for k, v in ini_dict.items()} # print final ...

Read More

Python - Ways to format elements of given list

Nizamuddin Siddiqui
Nizamuddin Siddiqui
Updated on 25-Mar-2026 3K+ Views

When working with lists containing numeric values, you often need to format them for better readability or presentation. Python provides several methods to format list elements, including list comprehension with string formatting, map() function, and modern f-string formatting. Using List Comprehension with % Formatting The traditional approach uses list comprehension with percentage formatting ? numbers = [100.7689454, 17.232999, 60.98867, 300.83748789] # Format to 2 decimal places using % formatting formatted = ["%.2f" % elem for elem in numbers] print(formatted) ['100.77', '17.23', '60.99', '300.84'] Using map() Function The map() function ...

Read More

Python - Ways to flatten a 2D list

Nizamuddin Siddiqui
Nizamuddin Siddiqui
Updated on 25-Mar-2026 1K+ Views

Flattening a 2D list means converting a nested list structure into a single-dimensional list. Python provides several methods to accomplish this task, each with different performance characteristics and use cases. Using itertools.chain.from_iterable() The chain.from_iterable() function efficiently flattens a 2D list by chaining all sublists together − from itertools import chain nested_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]] print("Initial list:", nested_list) ...

Read More

Python - Ways to find indices of value in list

Nizamuddin Siddiqui
Nizamuddin Siddiqui
Updated on 25-Mar-2026 274 Views

Finding indices of specific values in a list is a common task in Python programming. While the index() method finds the first occurrence, there are several ways to find all indices where a particular value appears in a list. Using enumerate() The enumerate() function returns both index and value, making it perfect for this task ? # initializing list numbers = [1, 3, 4, 3, 6, 7] print("Original list :", numbers) # using enumerate() to find indices for 3 indices = [i for i, value in enumerate(numbers) if value == 3] print("Indices of 3 :", ...

Read More

Python - Ways to create triplets from given list

Nizamuddin Siddiqui
Nizamuddin Siddiqui
Updated on 25-Mar-2026 446 Views

A triplet is a group of three consecutive elements from a list. Creating triplets from a given list means extracting all possible combinations of three adjacent elements. Python provides several approaches to accomplish this task efficiently. Using List Comprehension List comprehension provides a concise way to create triplets by slicing the list ? # List of words words = ['I', 'am', 'Vishesh', 'and', 'I', 'like', 'Python', 'programming'] # Using list comprehension to create triplets triplets = [words[i:i + 3] for i in range(len(words) - 2)] print("Triplets using list comprehension:") print(triplets) Triplets ...

Read More

Python - Ways to convert array of strings to array of floats

Nizamuddin Siddiqui
Nizamuddin Siddiqui
Updated on 25-Mar-2026 809 Views

When working with numerical data, you often need to convert arrays of string numbers to floating-point arrays for mathematical operations. NumPy provides several efficient methods to perform this conversion. Using astype() Method The astype() method is the most common way to convert data types in NumPy arrays − import numpy as np # Create array of string numbers string_array = np.array(["1.1", "1.5", "2.7", "8.9"]) print("Initial array:", string_array) # Convert to array of floats using astype float_array = string_array.astype(np.float64) print("Final array:", float_array) print("Data type:", float_array.dtype) Initial array: ['1.1' '1.5' '2.7' '8.9'] Final ...

Read More

Python - Using variable outside and inside the class and method

Nizamuddin Siddiqui
Nizamuddin Siddiqui
Updated on 25-Mar-2026 3K+ Views

Python is an object-oriented programming language where variables can be defined at different scopes. Understanding variable scope is crucial for writing clean, maintainable code. Variables can be defined outside classes (global scope), inside classes (class scope), or inside methods (local scope). Variables Defined Outside the Class (Global Variables) Variables defined outside any class or function have global scope and can be accessed from anywhere in the program ? # Variable defined outside the class (global scope) outVar = 'outside_class' print("Global access:", outVar) # Class one class Ctest: print("Inside class:", outVar) ...

Read More
Showing 6561–6570 of 8,549 articles
« Prev 1 655 656 657 658 659 855 Next »
Advertisements