Friday, 27 June 2025

Lists in Python

Lists in Python

✅ What is a List?

A list is a collection of items in Python. You can think of it like a basket that holds multiple values—like numbers, words, or both.

A list:

  • Is ordered (items have a specific position)
  • Is changeable (you can add, remove, or update items)
  • Allows duplicate values

๐ŸŸข How to Create a List

Use square brackets [ ] to create a list:

students = ["ansh", "aarav", "mishti"]
numbers = [1, 2, 3, 4]
mixed = [1, "hello", 3.5, True]

You can also create an empty list:

empty_list = []

๐Ÿ”ข Accessing Items in a List

You can use indexing to access items in a list. Python indexes start from 0.

students = ["ansh", "aarav", "mishti"]
print(students[0])  # ansh
print(students[1])  # aarav

You can also use negative indexing:

print(students[-1])  # mishti (last item)

✏️ Changing List Items

Lists are mutable, meaning you can change values.

fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango"
print(fruits)  # ['apple', 'mango', 'cherry']

➕ Adding Items to a List

append() – adds at the end:

fruits.append("orange")

insert() – adds at a specific position:

fruits.insert(1, "grape")  # inserts at index 1

❌ Removing Items from a List

remove() – removes by value:

fruits.remove("banana")

pop() – removes by index (default is last item):

fruits.pop()     # removes last
fruits.pop(0)    # removes first

clear() – removes all items:

fruits.clear()

๐Ÿ” Looping Through a List

You can use a for loop:

for fruit in fruits:
    print(fruit)

๐Ÿ“ Getting Length of a List

Use the len() function:

fruits = ["apple", "banana", "cherry"]
print(len(fruits))  # 3

๐Ÿ”„ Joining Two Lists

Use the + operator to combine two lists:

list1 = [1, 2]
list2 = [3, 4]
combined = list1 + list2  # [1, 2, 3, 4]

๐Ÿ” Checking for an Item

Use the in keyword:

if "apple" in fruits:
    print("Yes, apple is in the list")

๐Ÿงฉ List with Different Data Types

A list can have different types of data:

my_list = [10, "hello", True, 3.5]

๐Ÿงฑ Nested Lists

A list can contain another list (called a nested list):

nested = [1, 2, [3, 4]]
print(nested[2])      # [3, 4]
print(nested[2][1])   # 4

๐Ÿงช List Methods (Commonly Used)

Method Description
append() Adds item at the end
insert() Adds item at specific index
remove() Removes item by value
pop() Removes item by index
clear() Removes all items
sort() Sorts the list (ascending by default)
reverse() Reverses the list
index() Returns index of first match
count() Returns number of times item appears

๐Ÿ”ƒ Sorting a List

numbers = [3, 1, 4, 2]
numbers.sort()        # [1, 2, 3, 4]
numbers.sort(reverse=True)  # [4, 3, 2, 1]

๐Ÿ” Copying a List

list1 = [1, 2, 3]
list2 = list1.copy()

๐Ÿงฐ Converting List to Other Types

List to Tuple:

my_list = [1, 2, 3]
my_tuple = tuple(my_list)

✅ Summary

  • Lists are used to store multiple items in a single variable
  • Lists are ordered and changeable
  • You can add, remove, and update items
  • Lists support looping, sorting, nesting, and more
  • Lists are one of the most commonly used data structures in Python

Tuples in Python

Tuples in Python

✅ What is a Tuple?

A tuple is a collection in Python that lets you store multiple items in a single variable.

It is:

  • Ordered – items stay in the same order
  • Immutable – you cannot change the items once added
  • Allows duplicates – repeated values are okay

๐ŸŸจ How to Create a Tuple

Use round brackets () to create a tuple.

my_tuple = ("apple", "banana", "cherry")
print(my_tuple)

๐Ÿ“Œ You can also create a tuple without parentheses (Python understands it):

my_tuple = "apple", "banana", "cherry"

๐Ÿงช Tuple Examples

fruits = ("apple", "banana", "cherry")
numbers = (1, 2, 3, 4)
mixed = (1, "hello", 3.5)

✅ Tuples can contain:

  • Strings
  • Integers
  • Floats
  • Booleans
  • Other tuples!

๐Ÿ”ข Accessing Tuple Items

Use index numbers to access values (starting from 0):

colors = ("red", "blue", "green")
print(colors[0])  # red
print(colors[1])  # blue

You can also use negative indexing:

print(colors[-1])  # green (last item)

๐Ÿšซ Tuples are Immutable

Once a tuple is created, you can't change, add, or remove items:

numbers = (1, 2, 3)
# numbers[0] = 10  ❌ This will give an error

๐Ÿ“ Tuple Length

Use the len() function:

my_tuple = ("a", "b", "c")
print(len(my_tuple))  # 3

๐Ÿ” Looping Through a Tuple

Use a for loop to go through items:

colors = ("red", "blue", "green")
for color in colors:
    print(color)

๐Ÿ”„ Tuple Operations

✅ Concatenation:

t1 = (1, 2)
t2 = (3, 4)
result = t1 + t2  # (1, 2, 3, 4)

✅ Repetition:

t = ("hi",)
print(t * 3)  # ('hi', 'hi', 'hi')

๐Ÿ” Checking for an Item

fruits = ("apple", "banana", "cherry")
if "apple" in fruits:
    print("Yes, apple is there!")

๐Ÿงฉ Tuple with One Item?

You must add a comma if the tuple has only one item:

t = ("hello",)  # This is a tuple
x = ("hello")   # This is just a string

๐Ÿงฑ Nesting Tuples

Tuples can contain other tuples:

nested = (1, 2, (3, 4))

๐Ÿ“ฆ Tuple Packing and Unpacking

Packing:

info = ("Ansh", 7, "India")

Unpacking:

name, age, country = info
print(name)     # Ansh
print(age)      # 7
print(country)  # India

๐Ÿ”„ Converting Lists to Tuples

Use the tuple() function:

my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)  # (1, 2, 3)

๐Ÿ“Œ Tuple Methods

Method Description
count() Counts how many times an item appears
index() Returns the index of the first occurrence of an item

Example:

t = (1, 2, 3, 2, 4)
print(t.count(2))   # 2
print(t.index(3))   # 2

✅ When to Use Tuples?

Use tuples when:

  • You want data to be unchanged (read-only)
  • You are storing a fixed set of items
  • You want faster access than a list

๐ŸŽ“ Summary

  • Tuples use () to store multiple items
  • They are ordered and immutable
  • You can access items with indexing
  • Tuples are faster and safer than lists for fixed data
  • You can loop, count, and unpack tuples

Thursday, 26 June 2025

Python Built-in Datatypes

๐ŸŒŸ Introduction to Built-in Datatypes

Ever wondered how computers understand different types of data like numbers, names, or even true/false questions? That's where datatypes come into play! They're like labels that tell the computer what kind of value you're working with.

๐Ÿ” What Are Datatypes?

In programming, a datatype tells the interpreter what kind of value a variable holds. It could be a number, a piece of text, a list of things, or even something more complex.

๐Ÿ“Œ Why Datatypes Matter in Programming

Imagine trying to add two names together or divide a word by a number—it wouldn't make any sense! That's why programming languages use datatypes to prevent errors and organize your code.

⚖️ Static vs Dynamic Typing

  • Static Typing: You must declare the datatype before using it (like in Java or C++)
  • Dynamic Typing: The interpreter figures it out for you (like in Python)

Python uses dynamic typing, so it automatically understands what kind of data you're using.

๐Ÿงฑ Built-in vs User-defined Datatypes

  • Built-in Datatypes: Already available in the language (no need to define them)
  • User-defined Datatypes: Created by programmers using classes and objects

In this article, we're focusing on the built-in ones.

๐Ÿ”ข Numeric Datatypes

These are used when you want to store numbers.

1. Integer (int)

Used to store whole numbers, like 10, -3, or 0.

age = 25

2. Float (float)

Used to store decimal numbers, like 3.14, -0.5, or 99.99.

pi = 3.14159

3. Complex (complex)

Used in advanced mathematics, includes a real and an imaginary part.

z = 2 + 3j

๐Ÿ“š Sequence Datatypes

A sequence is an ordered collection of items.

1. String (str)

Used to store text, written in quotes.

name = "Alice"

You can use:

  • len(name) → Number of characters
  • name.upper() → Convert to uppercase

2. List (list)

Used to store multiple items in one variable. Lists are mutable (you can change them).

fruits = ["apple", "banana", "mango"]
fruits.append("orange")

3. Tuple (tuple)

Similar to lists but immutable (cannot be changed).

coordinates = (10, 20)

๐Ÿ”˜ Set Datatypes

Sets store unique items and do not maintain order.

1. Set (set)

numbers = {1, 2, 3, 3}
# Output: {1, 2, 3}

Useful for removing duplicates.

2. Frozen Set (frozenset)

An immutable version of a set.

fs = frozenset([1, 2, 3])

๐Ÿ—บ️ Mapping Datatype

Dictionary (dict)

Stores data in key-value pairs.

student = {
  "name": "John",
  "age": 16,
  "grade": "A"
}

Access using keys:

print(student["name"])  # Output: John

✅ Boolean Datatype

Boolean (bool)

Has only two values: True or False.

is_logged_in = True

Commonly used in conditions and loops.

๐Ÿšซ None Type

What is None?

None represents the absence of a value. It's like a blank placeholder.

result = None

You might use it when a variable is declared but not yet given a value.

๐Ÿ”„ Type Conversion and Type Casting

Sometimes you need to change one datatype into another.

Implicit Conversion

Python does it for you.

x = 5     # int
y = 2.5   # float
z = x + y  # float (Python converts int to float automatically)

Explicit Conversion

You do it manually.

x = 10
y = str(x)  # Convert int to string

๐Ÿ› ️ Built-in Functions for Datatypes

These make life easier:

  • type() → Returns the datatype
  • id() → Returns the memory address
  • isinstance() → Checks the type

Example:

num = 100
print(type(num))  # Output: <class 'int'>

๐Ÿ” Memory and Mutability

Mutable vs Immutable Types

  • Mutable: Can be changed (list, set, dict)
  • Immutable: Cannot be changed (int, float, str, tuple, frozenset)

Why does it matter? Because changing a mutable object affects its original reference.

๐Ÿ’ผ Real-Life Examples and Use-Cases

Using Lists to Store Marks

marks = [88, 76, 92, 85]

You can calculate average, highest marks, etc.

Using Dictionary for Employee Info

employee = {
  "name": "Ravi",
  "id": 103,
  "department": "HR"
}

You can easily update, search, and manage data using keys.

๐Ÿ Conclusion

Built-in datatypes are the building blocks of every Python program. Whether you're dealing with numbers, names, lists of groceries, or a record of students, Python has a datatype ready for it. Understanding these core types will help you write efficient and error-free code. So, the next time you're coding, remember—you're not just typing lines; you're instructing the computer using these datatypes!

❓ FAQs

  • What is the difference between list and tuple?
    A list is mutable (you can change it), while a tuple is immutable (you can't change it once created).
  • Can a set have duplicate values?
    No, sets automatically remove duplicates.
  • What is the default datatype of a number like 5?
    It's an integer (int).
  • Why is None used in Python?
    To represent a variable with no value or to initialize a variable for future use.
  • Are Python datatypes case-sensitive?
    Yes, Python is case-sensitive. True is a valid Boolean, but true is not.

Wednesday, 25 June 2025

Variables and Assignments in Python

Variables and Assignments in Python

๐Ÿ’ก What is a Variable?

A variable is like a container or a box in the computer's memory that stores a value.

Think of it like naming a jar to store something inside. The jar (variable) holds the value, and you can use that name anytime to get or change what's inside.

Example:

x = 10

Here:

  • x is the variable name
  • 10 is the value
  • = is the assignment operator

You can now use x in your program, and Python knows it means 10.

✅ Why Use Variables?

Variables:

  • Help you store data
  • Make your code easy to read and update
  • Let you perform calculations
  • Are used in almost every program!

๐Ÿ“ฅ Assignment in Python

In Python, we use the equal sign = to assign a value to a variable.

name = "Ansh"
age = 7
score = 92.5
  • name stores a word (string)
  • age stores a number (integer)
  • score stores a decimal (float)

✅ Summary

  • A variable stores a value using a name
  • The = sign is used to assign values
  • You can change or update variables any time
  • Variable names must follow certain rules
  • Python supports different data types like int, float, str, and bool
  • Use type() to check what kind of value a variable holds

Expressions and Numerical Types in Python

Expressions and Numerical Types in Python

๐Ÿ“Œ What is an Expression?

An expression is a combination of values, variables, and operators that Python can calculate (or evaluate) and give a result.

Example:

5 + 3
  • ๐Ÿ‘‰ This is an expression. It combines two numbers and a plus sign.
  • ๐Ÿ‘‰ The result of this expression is 8.
x = 10
y = x + 5
  • ๐Ÿ‘‰ Here, x + 5 is an expression.
  • ๐Ÿ‘‰ Python will calculate it and store 15 in y.

๐Ÿงฎ What are Numerical Types?

In Python, numbers come in different types based on how they are used.

There are mainly three types of numbers in Python:

1. int – Integer

These are whole numbers. They don't have any decimal point.

a = 5       # integer
b = -100    # negative integer

2. float – Floating Point Number

These are numbers with decimal points.

x = 3.14     # float
y = -0.5     # negative float

3. complex – Complex Numbers

These numbers have a real and an imaginary part.
Used mostly in higher math and science.

z = 2 + 3j   # complex number

You can check the type using type():

print(type(10))       # <class 'int'>
print(type(3.5))      # <class 'float'>
print(type(2 + 3j))   # <class 'complex'>

➕ Arithmetic Operators in Python

Python can do basic math using operators. These are:

Operator Meaning Example Result
+ Addition 5 + 3 8
- Subtraction 7 - 2 5
* Multiplication 4 * 3 12
/ Division 10 / 2 5.0
// Floor Division 10 // 3 3
% Modulus (remainder) 10 % 3 1
** Power 2 ** 3 8

✅ Summary

  • An expression is a combination of numbers, variables, and operators.
  • int, float, and complex are the 3 main number types in Python.
  • Python supports all basic math operations like +, -, *, /, %, etc.
  • Python follows the BODMAS rule for solving expressions.
  • You can use functions like abs(), round(), pow() with numbers.

Tuesday, 24 June 2025

Objects in Python

Objects in Python

What is an Object?

In real life, everything around us is an object — like a phone, a car, a ball, or a book.

Each object has:

  • Properties (like color, size, weight)
  • Actions (like ringing, driving, bouncing, or opening)

In Python, it's the same!
An object is something that stores data (like properties) and can do things (like actions).

Python is Object-Oriented

Python is called an Object-Oriented Programming (OOP) language.
This means Python works with objects in a smart way — we can create, use, and manage them easily.

Example of an Object

Let's take a simple example:

x = 5

Here, x is a variable, and it stores the value 5.

But actually, Python treats 5 as an object of type int (which stands for integer).

So:

  • 5 is an object
  • It has properties and actions

You can try:

print(type(x))

This will show:

<class 'int'>

This means x is an object of the class int.

Real-Life Analogy

Let's imagine a dog:

  • Its properties: name = "Bruno", color = "brown", age = 3
  • Its actions: bark

Key Takeaways

  • Everything in Python is an object
  • Objects have properties (data) and actions (methods)
  • Python is fundamentally object-oriented
  • Even simple variables reference objects with types

Introduction to Python

๐ŸŒŸ Introduction to Python

What is Python?

Python is a popular programming language. A programming language is like a set of instructions we give to the computer so it can do what we want — like solving math problems, showing messages, playing sounds, or making games.

Python is special because:

  • ✅ It is easy to read and write.
  • ✅ It looks simple — almost like English.
  • ✅ It is used by beginners as well as experts.
  • ✅ It can be used for many things — like making websites, apps, games, data analysis, artificial intelligence, and more.

Who made Python?

Python was created by Guido van Rossum in 1991. He named it Python after his favorite TV show called Monty Python's Flying Circus — not because of the snake!

Why do people like Python?

People like Python because:

  • ⭐ The rules (called syntax) are simple.
  • ⭐ It saves time because it needs fewer lines of code to do big tasks.
  • ⭐ It works on Windows, Mac, Linux — almost everywhere!
  • ⭐ It has a large community — so lots of help is available online.

Where is Python used?

Python is used in many fields:

  • ๐Ÿ’ป Web development — to build websites
  • ๐Ÿ“Š Data science — to study and understand data
  • ๐Ÿ•น️ Game development — to create games
  • ๐Ÿค– Artificial intelligence and machine learning — to make smart programs
  • ๐Ÿ“ฑ App development — to make apps for phones

How does Python look?

Here is a small example of Python code:

print("Hello, World!")

๐Ÿ‘‰ This code will make the computer show the message Hello, World!

Another example:

a = 5
b = 3
print(a + b)

๐Ÿ‘‰ This will show 8 on the screen because 5 + 3 = 8.

What do we need to write Python?

To start using Python, we need:

  • ✅ Python installed on your computer (from python.org)
  • ✅ A text editor (like Notepad or an app called IDLE that comes with Python)

Summary

๐Ÿ”น Python is a simple, powerful programming language.
๐Ÿ”น It is used for many purposes — from websites to robots.
๐Ÿ”น It is easy to learn, even if you are new to programming.

Sunday, 26 December 2021

Monday, 6 August 2012

Theory Assignment - 2

Smt. R.O.Patel Women’s MCA College, Morbi
MCA 2012-13
Subject Name: Fundamentals of Java Programming (Java) - 630002                 
MCA Semester: 3                                                Submission Date: ##/###/####
_____________________________________________________________________________________
Assignment-2

  1. What are the access specifiers available in java? Explain each of them. State which of these can be applied to a class and which can be applied to a member of a package.
  2. What is method overloading and overriding in java? Explain with example.
  3. What is interface? Explain with example.
  4. Explain -classpath and –d option of javac with example.
  5. What is String Buffer? Explain any 5 methods of String Buffer Class with syntax and example.
  6. What is pass by value and pass by reference in java? Explain with example.
  7. What are wrapper classes? Explain all in detail.
  8. Explain Comparable and Comparator interfaces.
  9. What is Exception handling? Explain types of exception available in java?
  10. Explain following keywords in detail. 
    1. abstract
    2. final
    3. super 
    4. this
    5. try
    6. catch
    7. throw
    8. throws
    9. finally       
 

Wednesday, 1 August 2012

Interview Questions in Java

Q:
What is the difference between an Interface and an Abstract class?
A:
An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
.
Q:
What is the purpose of garbage collection in Java, and when is it used?
A:
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.
Q:
What are pass by reference and passby value?
A:
Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed. 
Q:
What is the difference between a constructor and a method?
A:
A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

Q:
State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
A:
public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package
.
Q:
What is an abstract class?
A:
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

Q:
What is static in java?
A:
Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.
Q:
What is final?
A:
A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).
Q:
What if the main method is declared as private?
A:
The program compiles properly but at runtime it will give "Main method not public." message.
Q:
What if the static modifier is removed from the signature of the main method?
A:
Program compiles. But at runtime throws an error "NoSuchMethodError".
Q:
What if I write static public void instead of public static void?
A:
Program compiles and runs properly. 
Q:
What if I do not provide the String array as the argument to the method?
A:
Program compiles but throws a runtime error "NoSuchMethodError". 
Q:
What is the first argument of the String array in main method?
A:
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.
Q:
If I do not provide any arguments on the command line, then the String array of Main method will be empty or null?
A:
It is empty. But not null.
Q:
How can one prove that the array is not null but empty using one line of code?
A:
Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.
Q:
What environment variables do I need to set on my machine in order to be able to run Java programs?
A:
CLASSPATH and PATH are the two variables.
Q:
Can an application have multiple classes having main method?
A:
Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.
Q:
Can I have multiple main methods in the same class?
A:
No the program fails to compile. The compiler says that the main method is already defined in the class.
Q:
Do I need to import java.lang package any time? Why ?
A:
No. It is by default loaded internally by the JVM.
Q:
Can I import same package/class twice? Will the JVM load the package twice at runtime?
A:
One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.
Q:
What is Overriding?
A:
When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.
When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.
Q:
What are different types of inner classes?
A:
Nested -level classes, Member classes, Local classes, Anonymous classes
Nested -level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other -level class.
Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. -level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested -level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested -level class. The primary difference between member classes and nested -level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a
more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

Total Pageviews

Search This Blog

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display()

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display() ...