Featured Post

15 Python Tips : How to Write Code Effectively

Image
 Here are some Python tips to keep in mind that will help you write clean, efficient, and bug-free code.     Python Tips for Effective Coding 1. Code Readability and PEP 8  Always aim for clean and readable code by following PEP 8 guidelines.  Use meaningful variable names, avoid excessively long lines (stick to 79 characters), and organize imports properly. 2. Use List Comprehensions List comprehensions are concise and often faster than regular for-loops. Example: squares = [x**2 for x in range(10)] instead of creating an empty list and appending each square value. 3. Take Advantage of Python’s Built-in Libraries  Libraries like itertools, collections, math, and datetime provide powerful functions and data structures that can simplify your code.   For example, collections.Counter can quickly count elements in a list, and itertools.chain can flatten nested lists. 4. Use enumerate Instead of Range     When you need both the index ...

Python 'getsizeof' Command the Real Purpose

Here's a sample python program to get the size of a List array.  Getting the number of elements present in a List is not easy. So how to get this? To do you need the 'getsizeof' command.

Import 'sys' Library.

You need to import the 'sys' library to use the SIZE commands. 

>>> import sys

Congrats to you since you have now imported the SYS library. The command name is "getsizeof".

Check the below example.

print("An Integer:")
i = int(100)
print(sys.getsizeof(i))

The result will be: 100

What is the size command?  - is to get the size of elements. It gives the result based on the object you are being used. Suppose, if you use Strings, you will get String length.

Python Command to get the Size of an Object


How to use the 'getsizeof' command?

Example:1

print("Empty string:")
empty_string = ""
print(sys.getsizeof(empty_string))

Example:2

print("A normal string")
s = "Hello world"
print(sys.getsizeof(s))

Example:3

print("Increasing string:")
for i in range(0,5):
empty_string = empty_string + chr(i)
print(sys.getsizeof(empty_string))

Sources

Comments

Popular posts from this blog

How to Fix datetime Import Error in Python Quickly

SQL Query: 3 Methods for Calculating Cumulative SUM

Big Data: Top Cloud Computing Interview Questions (1 of 4)