Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Articles
Page 3 of 855
What's the difference between lists and tuples in Python?
Python has two main sequence data types for storing collections: lists and tuples. Both can store multiple items of different types, but they differ significantly in mutability, syntax, and use cases. Key Differences Overview Feature List Tuple Mutability Mutable (changeable) Immutable (unchangeable) Syntax Square brackets [ ] Parentheses ( ) Performance Slower Faster Use Case Dynamic data Fixed data Creating Lists and Tuples # Creating a list fruits_list = ['apple', 'banana', 'orange'] print("List:", fruits_list) # Creating a tuple fruits_tuple = ...
Read MoreHow to get the second-to-last element of a list in Python?
Python lists support negative indexing, where -1 refers to the last element and -2 refers to the second-to-last element. This makes accessing elements from the end of a list straightforward. Using Negative Indexing The most direct way is using index -2 ? numbers = [1, 2, 3, 4, 5] second_last = numbers[-2] print(second_last) 4 Handling Edge Cases For lists with fewer than 2 elements, accessing [-2] raises an IndexError. Use a conditional check ? def get_second_last(items): if len(items) >= 2: ...
Read MoreHow do I sort a list of dictionaries by values of the dictionary in Python?
In this article, we will show how to sort a list of dictionaries by the values of the dictionary in Python. Sorting has always been a useful technique in everyday programming. Python dictionaries are frequently used in applications ranging from competitive programming to web development (handling JSON data). Being able to sort dictionaries by their values is essential for data processing and analysis. We'll explore two main approaches to accomplish this task ? Using sorted() and itemgetter Using sorted() and lambda functions Understanding Python Dictionaries A dictionary is Python's implementation of an associative ...
Read MoreHow can I get last 4 characters of a string in Python?
Getting the last 4 characters of a string is a common task in Python. You can achieve this using string slicing with negative indices, which count from the end of the string. Using Negative Slicing The slice operator [-4:] starts from the 4th character from the end and goes to the end of the string ? text = "Thanks. I am fine" last_four = text[-4:] print(last_four) fine Examples with Different Strings Here are more examples showing how negative slicing works ? # Different string examples word1 = "Python" ...
Read MoreCan we assign a reference to a variable in Python?
In Python, variables work differently than in languages like C/C++. Understanding this difference is crucial for Python programming. In C/C++, a variable represents a named location in memory, but Python variables are simply names that refer to objects. Variables in C/C++ vs Python C++ Variable Behavior In C++, variables are memory locations. When you assign one variable to another, it creates a copy ? int x = 5; int y = x; // Creates a copy of x's value Each variable has its own memory address ? cout
Read MoreHow can we unpack a string of integers to complex numbers in Python?
A string containing two integers separated by a comma can be unpacked and converted into a complex number. Python provides several approaches to achieve this conversion. Method 1: Using split() and Indexing First, split the string into a list of string digits, then convert each part to integers for the complex() function − s = "1, 2".split(", ") print("Split result:", s) # Convert to complex number result = complex(int(s[0]), int(s[1])) print("Complex number:", result) Split result: ['1', '2'] Complex number: (1+2j) Method 2: Using Unpacking with map() Use map() to ...
Read MoreWhat is the best way to handle list empty exception in Python?
When working with lists in Python, you may encounter situations where you need to handle empty list exceptions. A list is an ordered sequence of elements accessed using indices from 0 to length-1. If you try to access an index beyond this range or perform operations on an empty list, Python raises an IndexError exception. Understanding IndexError with Empty Lists The most common scenario is when using methods like pop() on an empty list. Here's how to handle it properly using try-except ? numbers = [1, 2, 3] while True: try: ...
Read MoreHow can import python module in IDE environment available in tutorialspoint?
The TutorialsPoint online Python IDE provides a convenient browser-based environment for running Python code. While it supports Python's built-in standard library modules, importing external third-party packages has limitations. Available Standard Library Modules The TutorialsPoint Python IDE comes with most standard library modules pre-installed. You can import these modules directly without any special setup ? import math import datetime import random print("Square root of 16:", math.sqrt(16)) print("Current date:", datetime.date.today()) print("Random number:", random.randint(1, 10)) Square root of 16: 4.0 Current date: 2024-01-15 Random number: 7 How to Import Modules in TutorialsPoint IDE ...
Read Moreclassmethod() in Python
A class method receives the class itself as its first argument (conventionally named cls). This allows us to call the method on the class without first creating an instance. We use the @classmethod decorator before the method declaration to define a class method. Key Features of Class Methods A classmethod is bound to a class and does not depend on the instantiation of a class to be used. A classmethod can modify class attributes which propagate to all instances of the class. The first parameter is always the ...
Read MorePython eval()
The eval() method parses the expression passed to it and runs the expression within the program. In other words, it interprets a string as code inside a Python program. Syntax The syntax for eval() is as below − eval(expression, globals=None, locals=None) Where expression − The Python expression passed to the method as a string. globals − A dictionary of available global methods and variables (optional). locals − A dictionary of available local methods and variables (optional). Basic Example Here's a simple example showing ...
Read More