IOT Mod2 Q2a
IOT Mod2 Q2a
Features
SRAM: 2KB
EEPROM: 1KB
• Arduino UNO supports 3 types of communication protocols, used for interfacing with
third-party peripherals, named:
Serial ProtocolI2C
Protocol SPI
Protocol
• Apart from USB, a battery or AC to DC adopter can also be used to power the board.
Arduino UNO comes with a USB interface i.e. USB port is added on the board to develop serial
communication with the computer.
(b). Arduino boards come in various types, each designed for specific tasks and applications. Here are some
of the most common types of Arduino boards:
1. Arduino Uno: This is one of the most popular and widely used Arduino boards. It features an
ATmega328P microcontroller, digital and analog I/O pins, USB interface, power jack, and a reset
button. It's great for beginners and general-purpose projects.
2. Arduino Nano: The Nano is a compact version of the Uno, making it suitable for projects with space
constraints. It has similar features to the Uno but in a smaller form factor.
3. Arduino Mega: The Mega is designed for projects that require a large number of I/O pins and more
memory. It uses the ATmega2560 microcontroller and has more digital and analog pins compared to
the Uno or Nano.
4. Arduino Leonardo: The Leonardo uses the ATmega32u4 microcontroller and has built-in USB
communication, which allows it to act as a USB HID (Human Interface Device). This board is great
for projects involving keyboard or mouse emulation.
5. Arduino Due: The Due is based on the ARM Cortex-M3 processor, making it more powerful than
the AVR-based boards like Uno or Mega. It has a higher clock speed, more memory, and is suitable
for projects that require more processing power.
6. Arduino MKR Series: The MKR series includes boards like the MKR1000, MKR Zero, MKR Wi-
Fi 1010, etc. These boards are designed for IoT (Internet of Things) projects and feature built-in
connectivity options such as Wi-Fi, Bluetooth, or LoRa.
7. Arduino Nano 33 IoT: This board combines the compact size of the Nano with IoT capabilities,
including Wi-Fi and Bluetooth connectivity. It's suitable for creating IoT applications and projects
that require wireless communication.
8. Arduino Pro Mini: The Pro Mini is a minimalistic version of the Uno, designed for projects where
space is limited, and cost-effectiveness is crucial. It lacks some features like USB connectivity and
requires an external programmer.
9. Arduino LilyPad: The LilyPad boards are designed for wearable electronics and e-textiles projects.
They are small, round boards with sewable pads, making them ideal for integrating into clothing or
fabric-based projects.
10. Arduino Nano Every: This board is an upgraded version of the Nano with more memory and
improved features while maintaining a compact size. It's suitable for a wide range of projects,
especially those requiring a balance between performance and size.
These are just a few examples of the different types of Arduino boards available. Each board has its
strengths and is suitable for specific types of projects, so choosing the right one depends on your project
requirements and constraints.
List the Components on Arduino UNO Board and explain the functionality
2 of each
(or)
The Arduino Uno is a popular microcontroller board based on the ATmega328P chip. It's widely used in
hobbyist projects, educational settings, and prototyping due to its ease of use and versatility. Here are the
main components on the Arduino Uno board and their functionalities:
1. Microcontroller (ATmega328P): This is the brain of the Arduino Uno board. It's responsible for
executing the code uploaded to the board and controlling all other components based on the
instructions in the code.
2. Crystal Oscillator: The Arduino Uno board uses a 16 MHz crystal oscillator. It provides the clock
signal needed for the microcontroller to operate at its specified frequency.
3. Reset Button: The reset button allows you to restart the microcontroller, causing it to begin
executing the code from the beginning.
4. Power Connector: This is where you connect an external power source to power the Arduino Uno
board. The board can be powered using a USB cable connected to a computer or a DC power
adapter.
5. Voltage Regulator (5V and 3.3V): The voltage regulator ensures that the voltage supplied to the
board remains stable. It regulates the incoming voltage to 5V for the main board and 3.3V for certain
components like the ATmega328P's ADC (Analog-to-Digital Converter).
6. Digital Input/Output Pins (GPIO): The Arduino Uno has a total of 14 digital input/output pins,
labeled from 0 to 13. These pins can be used to read digital inputs (like switches or sensors) or to
output digital signals (like controlling LEDs or relays).
7. Analog Input Pins: There are 6 analog input pins (labeled A0 to A5) on the Arduino Uno board.
These pins can read analog voltages from sensors or other analog devices. The ATmega328P's ADC
converts these analog signals into digital values that can be processed by the microcontroller.
8. PWM (Pulse Width Modulation) Pins: Some of the digital pins on the Arduino Uno board (pins 3,
5, 6, 9, 10, and 11) support PWM output. PWM is used to simulate analog output by rapidly
switching the pin on and off at varying duty cycles, allowing you to control the brightness of LEDs
or the speed of motors, for example.
9. USB Interface: The Arduino Uno board has a USB interface (USB Type-B connector) that allows
you to connect it to a computer for programming and power supply. The USB connection also
enables serial communication between the Arduino board and the computer for debugging and data
transfer.
10. TX/RX LEDs: These LEDs (labeled TX and RX) indicate data transmission and reception activity
between the Arduino board and the computer via the USB interface. They blink when data is being
sent or received.
11. ICSP Header: The In-Circuit Serial Programming (ICSP) header allows you to program the
ATmega328P microcontroller using an external programmer or another Arduino board. It provides
an alternative method for programming the microcontroller if needed.
12. Voltage Reference (AREF) Pin: The AREF pin is used to provide an external reference voltage for
the ATmega328P's ADC when using analog sensors. It allows you to use a specific voltage range for
analog readings instead of relying on the default internal reference voltage.
(b). To interface an LED with an Arduino Uno and write a program to blink the LED, you'll need the
following components:
1. Arduino Uno board
2. LED (any color)
3. Resistor (around 220 ohms is commonly used to limit current to the LED)
4. Breadboard (optional but recommended for easy connections)
5. Jumper wires
Here are the steps to connect the LED to the Arduino Uno and write a program to blink it:
1. Connect the Components:
• Insert the LED into the breadboard. Make sure the longer leg (anode, positive) of the LED is
connected to one side of the breadboard, and the shorter leg (cathode, negative) is connected
to the other side.
• Connect one end of the resistor to the same row as the LED's cathode.
• Connect the other end of the resistor to a GND (ground) pin on the Arduino Uno board using
a jumper wire.
• Connect the anode (longer leg) of the LED to digital pin 13 on the Arduino Uno using a
jumper wire.
2. Write the Arduino Sketch (Program): Open the Arduino IDE on your computer and create a new
sketch (File -> New). Copy and paste the following code into the Arduino IDE:
// Define the LED pin
const int ledPin = 13;
void setup() {
// Initialize the LED pin as an output
pinMode(ledPin, OUTPUT);
}
void loop() {
// Turn the LED on
digitalWrite(ledPin, HIGH);
delay(1000); // Wait for 1 second (1000 milliseconds)
The software used for writing, compiling & uploading code to Arduino boards is called Arduino
IDE (Integrated Development Environment), which is free to download from Arduino Official Site.
◎ Before you start programming, double check that correct board is selected under Tools
→ Board.
Now, you can start playing with Arduino.
◎ The Arduino Uno can be programmed with the Arduino software. Select "Arduino Uno
from the Tools > Board menu (according to the microcontroller on your board).
◎ All the peripheral connected with Computers are using Serial Port.
You can check port for Arduino Uno in Device Manger.
The installation procedure for the Arduino IDE involves the following steps:
1. Download the Arduino IDE Software:
• Visit the Arduino website and download the Arduino IDE software compatible with your
operating system (Windows, macOS, or Linux).
• Ensure you select the correct version that matches your operating system.
• After downloading, unzip the file to access the installation files.
2. Power up Your Board:
• Connect your Arduino board to your computer using a USB cable. The board can draw power
from the USB connection or an external power supply, depending on the model.
• Make sure the power source is correctly selected, especially for boards like Arduino
Diecimila that require manual configuration.
• Upon connecting, the green power LED on the board should illuminate, indicating power
supply.
3. Launch Arduino IDE:
• Unzip the downloaded Arduino IDE folder and locate the application icon with an infinity
label (application.exe).
• Double-click the icon to launch the Arduino IDE software on your computer.
4. Open Your First Project:
• After opening the Arduino IDE, you have the option to create a new project or open an
existing project example.
• To create a new project, go to File → New. To open an existing example, navigate to File →
Example → Basics → Blink (or any other example).
• The Blink example is a common starting point that turns an LED on and off with a time
delay.
5. Select Your Arduino Board:
• To ensure successful program uploading, select the correct Arduino board model in the IDE.
• This step is crucial to avoid errors during the uploading process and to ensure compatibility
with the specific Arduino board you are using.
By following these steps, you can successfully install the Arduino IDE on your computer, power up your
Arduino board, launch the IDE, open a project, and select the appropriate board for your programming
needs.
(or)
The Arduino Integrated Development Environment (IDE) is a software application used for writing,
compiling, and uploading code to Arduino boards. Here's a step-by-step guide to installing the
Arduino IDE on your computer:
1. Download Arduino IDE: Go to the official Arduino website at https://www.arduino.cc/en/software
and download the Arduino IDE for your operating system (Windows, macOS, Linux).
2. Install Arduino IDE on Windows:
• Once the download is complete, double-click the downloaded installer (e.g., "arduino-xxxx-
windows.exe") to start the installation process.
• Follow the on-screen instructions in the installation wizard. You can choose the installation
directory, shortcuts, and additional options during the installation.
• Click "Install" to begin installing the Arduino IDE on your Windows computer.
• After the installation completes, you can launch the Arduino IDE from the desktop shortcut
or the Start menu.
3. Install Arduino IDE on macOS:
• Open the downloaded Arduino IDE disk image (e.g., "arduino-xxxx-macosx.dmg").
• Drag the Arduino application icon to the Applications folder to install it.
• Eject the Arduino disk image after installation.
• You can now open the Arduino IDE from the Applications folder or Launchpad.
4. Install Arduino IDE on Linux:
• Extract the downloaded Arduino IDE archive (e.g., "arduino-xxxx-linux64.tar.xz") to a
desired location on your Linux system.
• Open a terminal and navigate to the extracted Arduino IDE folder using the cd command. For
example:
cd path/to/arduino-xxxx
• Run the ./install.sh script to install the Arduino IDE system-wide. You may need to use sudo
for administrative privileges:
sudo ./install.sh
• After the installation is complete, you can launch the Arduino IDE from the Applications
menu or by typing arduino in the terminal.
5. First-Time Setup:
• Open the Arduino IDE on your computer.
• Go to File -> Preferences (Arduino -> Preferences on macOS).
• In the "Additional Board Manager URLs" field, add the URL for the board packages you
want to install (e.g., for ESP8266 boards, add
"http://arduino.esp8266.com/stable/package_esp8266com_index.json").
• Click "OK" to save the preferences.
6. Install Additional Board Packages (if needed):
• Go to Tools -> Board -> Boards Manager.
• Search for the board package you want to install (e.g., "esp8266" for ESP8266 boards).
• Click "Install" to download and install the selected board package.
7. Connect Arduino Board (if applicable):
• If you have an Arduino board, connect it to your computer using a USB cable.
• Wait for your computer to recognize the Arduino board and install any necessary drivers (this
step is usually automatic for most operating systems).
Now you have successfully installed the Arduino IDE on your computer and can start writing,
compiling, and uploading code to Arduino boards.
(b).
i) AnalogRead():
• analogRead() is used to read analog voltage values from analog pins on the Arduino board.
• Analog pins on Arduino (e.g., A0, A1, etc.) can read voltages in the range of 0 to 5 volts.
• The analogRead() function converts the analog voltage into a digital value ranging from 0 to 1023
(10-bit resolution), where 0 represents 0 volts, and 1023 represents 5 volts.
• Syntax:
int sensorValue = analogRead(A0); // Reads analog voltage from pin A0
• In this example, sensorValue will store the digital value read from analog pin A0.
ii) AnalogWrite():
• analogWrite() is used to generate a PWM (Pulse Width Modulation) signal on a digital pin to
simulate analog output.
• PWM is a technique where the output pin is rapidly switched on and off at varying duty cycles to
control the average voltage applied to devices like LEDs or motors, effectively controlling their
brightness or speed.
• Syntax:
• The pin parameter specifies the digital pin number (e.g., 3, 5, 6, 9, 10, or 11 on most Arduino
boards) where PWM output will be generated.
• The value parameter ranges from 0 (minimum) to 255 (maximum), representing the duty cycle of the
PWM signal (0 for always off, 255 for always on, and values in between for varying levels of
brightness/speed).
iii) DigitalRead():
• digitalRead() is used to read digital logic values (HIGH or LOW) from digital pins on the Arduino
board.
• Digital pins can be used to interface with digital sensors, switches, buttons, or to read digital outputs
from other devices.
• Syntax:
int buttonState = digitalRead(2); // Reads digital logic value from pin 2
• In this example, buttonState will store the value HIGH (1) or LOW (0) depending on the logic level
detected at digital pin 2.
iv) DigitalWrite():
• digitalWrite() is used to set the digital output state (HIGH or LOW) on digital pins.
• It's commonly used to control LEDs, relays, or to send digital signals to other devices.
• Syntax:
digitalWrite(pin, HIGH); // Sets specified pin to HIGH (5V)
digitalWrite(pin, LOW); // Sets specified pin to LOW (0V)
• The pin parameter specifies the digital pin number, and the second parameter (HIGH or LOW) sets
the output state accordingly.
These functions are fundamental in Arduino programming and are used extensively to interact with both
analog and digital components connected to the Arduino board.
DHT;
void setup()
{
Serial.begin(9600);
lcd.begin(16,2);
}
void loop()
{
int val= DHT.read11(7); int
cel= DHT.temperature; int
humi=DHT.humidity;
lcd.print("Temperature: ");
delay(1000);
lcd.clear();
}
(b). To interface an IR sensor with Arduino and explain with an application programming, you can follow
these steps:
Interfacing IR Sensor with Arduino:
1. Hardware Setup:
• Connect the IR sensor module to the Arduino board by linking the VCC pin to 5V, GND pin
to GND, and the OUT pin to a digital pin (e.g., pin 10 or 13).
• Ensure the connections are secure and follow the correct pinout for the IR sensor module.
3. Application Programming:
• Develop an application scenario where the IR sensor is used, such as an obstacle avoidance
robot or a motion detection system.
• Define the behavior of the system based on the sensor readings. For example, if an obstacle is
detected, activate an LED or trigger a specific action.
• Utilize conditional statements in your code to respond to different sensor inputs and create a
responsive system.
Example Code Snippet:
cpp
int IRsensor = 10; // Connect IR sensor module to Arduino pin 10
int LED = 13; // Connect LED to Arduino pin 13
void setup() {
Serial.begin(9600); // Initialize Serial communication
pinMode(IRsensor, INPUT); // Set IR Sensor pin as INPUT
pinMode(LED, OUTPUT); // Set LED pin as OUTPUT
}
void loop() {
int sensorStatus = digitalRead(IRsensor); // Read sensor status
if (sensorStatus == HIGH) {
digitalWrite(LED, HIGH); // Turn on LED if obstacle is detected
} else {
digitalWrite(LED, LOW); // Turn off LED if no obstacle is detected
}
}
By following these steps and incorporating the provided code snippet, you can successfully interface an IR
sensor with Arduino and create a functional application that responds to the sensor's input. This setup can be
further expanded and customized based on the specific requirements of your project.
(or)
To interface an IR (Infrared) sensor with Arduino and create an application, we'll use an IR receiver module
commonly used for receiving signals from remote controls. The IR receiver module can detect infrared
signals from IR remote controls and convert them into electrical signals that can be processed by the
Arduino. Here's how to interface an IR sensor with Arduino and create a simple application to control an
LED using an IR remote control:
Hardware Required:
1. Arduino Uno or compatible board
2. IR receiver module (e.g., TSOP38238)
3. IR remote control (compatible with the IR receiver module)
4. LED
5. Resistor (220 ohms)
6. Breadboard
7. Jumper wires
Circuit Connections:
1. Connect the IR receiver module to the Arduino as follows:
• Connect the VCC pin of the IR receiver module to 5V on the Arduino.
• Connect the GND pin of the IR receiver module to GND on the Arduino.
• Connect the OUT pin of the IR receiver module to digital pin 11 on the Arduino.
2. Connect the LED to the Arduino:
• Connect the positive (anode) leg of the LED to digital pin 13 on the Arduino through a 220-
ohm resistor.
• Connect the negative (cathode) leg of the LED to GND on the Arduino.
3. Make sure your Arduino board is connected to your computer via USB for programming.
Arduino Sketch (Code):
Here's an example Arduino sketch that reads IR signals from a remote control using the IR receiver module
and uses those signals to control an LED:
#include <IRremote.h>
IRrecv irrecv(IR_RECEIVER_PIN);
decode_results results;
void setup() {
pinMode(LED_PIN, OUTPUT);
irrecv.enableIRIn(); // Start the IR receiver
}
void loop() {
if (irrecv.decode(&results)) { // Check if IR signal is received
unsigned long irCode = results.value; // Get the received IR code
// Check if the received IR code matches the code for a specific button
if (irCode == 0xFFA25D) { // Example: Power button code
digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Toggle the LED state
}
8 a)State any six reasons, why you must consider writing software
applications in Python.
b) State which of the following python statements are valid and invalid.
a.print("ksk", + "123")
b. print("ksk" '+' "123")
c. print("ksk", '+', "123")
print('ABC is a "technological" University')
print(2 + '3')
print('2' * 3)
(a). There are several reasons why Python is a popular choice for writing software applications. Here are six
key reasons why you should consider writing software applications in Python:
1. Readability and Simplicity: Python's syntax and readability make it easy to write and understand
code. Its clean and straightforward syntax resembles English-like language, which reduces the
complexity of code and makes it more readable.
2. Versatility and Flexibility: Python is a versatile language that supports multiple programming
paradigms such as procedural, object-oriented, and functional programming. It can be used for
various types of applications, including web development, data analysis, scientific computing,
artificial intelligence, machine learning, and automation.
3. Rich Standard Library: Python comes with a comprehensive standard library that provides ready-
to-use modules and functions for a wide range of tasks. This eliminates the need to write code from
scratch for common functionalities like file handling, networking, data manipulation, and more,
saving development time and effort.
4. Large Ecosystem of Libraries and Frameworks: Python has a vast ecosystem of third-party
libraries and frameworks that extend its capabilities and facilitate rapid application development.
Popular libraries and frameworks include Django and Flask for web development, NumPy and
pandas for data analysis, TensorFlow and PyTorch for machine learning, and Matplotlib and Seaborn
for data visualization.
5. Cross-Platform Compatibility: Python is a cross-platform language, meaning that Python code can
run on various operating systems such as Windows, macOS, Linux, and Unix without major
modifications. This cross-platform compatibility makes Python suitable for developing applications
that need to run on different environments.
6. Community Support and Documentation: Python has a large and active community of developers,
which means there is ample support available through online forums, tutorials, documentation, and
resources. The Python community continuously contributes to the improvement and evolution of the
language, ensuring its relevance and usability for developers.
Overall, Python's readability, versatility, rich ecosystem, cross-platform compatibility, and strong
community support make it an excellent choice for writing software applications across different domains
and use cases.
A) here are six arithmetic operators in Python along with examples for each:
1. Addition (+): The addition operator is used to add two numbers together.
a = 5 b = 3 result = a + b print("Result of addition:", result) # Output: 8
2. Subtraction (-): The subtraction operator is used to subtract one number from another.
x = 10 y = 7 result = x - y print("Result of subtraction:", result) # Output: 3
4. Division (/): The division operator is used to divide one number by another. In Python 3, division
always returns a float.
m = 20 n = 5 result = m / n print("Result of division:", result) # Output: 4.0
5. Floor Division (//): The floor division operator divides one number by another and returns the
quotient as an integer, discarding any fractional part.
x = 13 y = 5 result = x // y print("Result of floor division:", result) # Output: 2
6. Modulo (%): The modulo operator returns the remainder when one number is divided by another.
a = 10 b = 3 result = a % b print("Remainder after division:", result) # Output: 1
These are the basic arithmetic operators in Python used for common mathematical operations.
b) Assignment operators in Python are used to assign values to variables. Here are six assignment operators along
with examples for each:
1. Equal (=): The equal sign (=) is the simplest assignment operator, used to assign the value on its
right to the variable on its left.
x = 5 print(x) # Output: 5
2. Addition and Assignment (+=): The += operator adds the value on its right to the variable on its left
and assigns the result to the variable.
x = 5 x += 3 # Equivalent to x = x + 3 print(x) # Output: 8
3. Subtraction and Assignment (-=): The -= operator subtracts the value on its right from the variable
on its left and assigns the result to the variable.
y = 10 y -= 4 # Equivalent to y = y - 4 print(y) # Output: 6
4. Multiplication and Assignment (*=): The *= operator multiplies the value on its right with the
variable on its left and assigns the result to the variable.
z = 2 z *= 6 # Equivalent to z = z * 6 print(z) # Output: 12
5. Division and Assignment (/=): The /= operator divides the variable on its left by the value on its
right and assigns the result to the variable.
a = 15 a /= 3 # Equivalent to a = a / 3 print(a) # Output: 5.0 (Note: In Python 3, division always returns a
float)
6. Modulo and Assignment (%=): The %= operator takes the remainder of the variable on its left
divided by the value on its right and assigns the result to the variable.
b = 17 b %= 5 # Equivalent to b = b % 5 print(b) # Output: 2
These assignment operators provide a shorthand way to perform arithmetic operations and update variables
in Python.
c) Comparison operators in Python are used to compare values and return boolean results (True or False). Here are all
the comparison operators in Python along with examples for each:
1. Equal to (==): This operator checks if two values are equal.
x = 5 y = 5 print(x == y) # Output: True
2. Not Equal to (!=): This operator checks if two values are not equal.
a = 10 b = 7 print(a != b) # Output: True
3. Greater than (>): This operator checks if the left operand is greater than the right operand.
m = 15 n = 10 print(m > n) # Output: True
4. Less than (<): This operator checks if the left operand is less than the right operand.
p = 8 q = 12 print(p < q) # Output: True
5. Greater than or equal to (>=): This operator checks if the left operand is greater than or equal to
the right operand.
x = 7 y = 5 print(x >= y) # Output: True
6. Less than or equal to (<=): This operator checks if the left operand is less than or equal to the right
operand.
a = 10 b = 10 print(a <= b) # Output: True
These comparison operators are frequently used in conditional statements, loops, and other control structures
to make decisions based on the relationships between values.
a) In Python, break, continue, and pass are control flow statements used to modify the flow of execution in loops or
conditional blocks.
1. break Statement: The break statement is used to exit the current loop prematurely, regardless of the
loop's condition. When encountered, it immediately terminates the loop and transfers control to the
statement immediately following the loop.
Example of break statement:
# Find the first occurrence of a number divisible by 5 in a list numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for num
in numbers: if num % 5 == 0: print("First number divisible by 5:", num) break
2. continue Statement: The continue statement is used to skip the rest of the current iteration of a loop
and proceed to the next iteration. When encountered, it jumps back to the top of the loop, bypassing
the remaining code within the loop's body.
Example of continue statement:
# Print all even numbers in a list, skipping odd numbers numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for num in
numbers: if num % 2 != 0: continue print("Even number:", num)
3. pass Statement: The pass statement is a null operation that does nothing when executed. It is
typically used as a placeholder where syntactically a statement is required but no action needs to be
taken.
Example of pass statement:
# Define a function that does nothing def dummy_function(): pass # A placeholder class definition class
MyClass: pass # A conditional block where no action is needed x = 10 if x < 5: pass else: print("x is greater
than or equal to 5")
In summary, break is used to exit a loop prematurely, continue is used to skip the current iteration of a
loop, and pass is used as a placeholder for syntactic correctness when no action is needed.
b) let's differentiate between lists, tuples, and sets in Python along with suitable examples for each:
1. List:
• Lists are ordered collections of items that are mutable, meaning their elements can be
changed after creation.
• Elements in a list are enclosed in square brackets [ ] and separated by commas.
• Lists allow duplicate elements, and their elements can be of different data types.
• Lists support indexing and slicing operations to access and manipulate elements.
Example of a list:
my_list = [1, 2, 3, 4, 'apple', 'banana', 'cherry'] print(my_list) # Output: [1, 2, 3, 4, 'apple', 'banana',
'cherry'] # Accessing elements by index print(my_list[0]) # Output: 1 # Modifying an element
my_list[4] = 'orange' print(my_list) # Output: [1, 2, 3, 4, 'orange', 'banana', 'cherry']
2. Tuple:
• Tuples are ordered collections of items that are immutable, meaning their elements
cannot be changed after creation.
• Elements in a tuple are enclosed in parentheses ( ) and separated by commas.
• Tuples allow duplicate elements, and their elements can be of different data types.
• Tuples support indexing and slicing operations to access elements.
Example of a tuple:
my_tuple = (1, 2, 3, 4, 'apple', 'banana', 'cherry') print(my_tuple) # Output: (1, 2, 3, 4, 'apple',
'banana', 'cherry') # Accessing elements by index print(my_tuple[0]) # Output: 1
3. Set:
• Sets are unordered collections of unique items that are mutable, meaning their elements
can be changed after creation.
• Elements in a set are enclosed in curly braces { } and separated by commas.
• Sets do not allow duplicate elements, and their elements must be hashable (immutable
data types).
• Sets do not support indexing or slicing operations, but they offer operations like union,
intersection, and difference.
Example of a set:
my_set = {1, 2, 3, 4, 'apple', 'banana', 'cherry'} print(my_set) # Output: {1, 2, 3, 4, 'apple', 'banana',
'cherry'} # Adding an element to the set my_set.add('orange') print(my_set) # Output: {1, 2, 3, 4,
'apple', 'banana', 'cherry', 'orange'} # Removing an element from the set my_set.remove(2)
print(my_set) # Output: {1, 3, 4, 'apple', 'banana', 'cherry', 'orange'}
In summary, lists are mutable ordered collections, tuples are immutable ordered collections, and sets
are mutable unordered collections of unique elements. Each data structure has its own characteristics
and is suitable for different use cases based on requirements such as mutability, ordering, and
uniqueness.
b)Both pop() and sort() are built-in methods of the list class in Python.
1. pop() method:
• The pop() method is used to remove and return the element at a specified index (default is the
last element) from a list.
• It modifies the list in place.
Example using pop() method:
my_list = [1, 2, 3, 4, 5] # Remove and return the last element popped_element = my_list.pop()
print("Popped element:", popped_element) # Output: Popped element: 5 print("List after popping:", my_list)
# Output: List after popping: [1, 2, 3, 4] # Remove and return the element at index 1 popped_element =
my_list.pop(1) print("Popped element at index 1:", popped_element) # Output: Popped element at index 1: 2
print("List after popping:", my_list) # Output: List after popping: [1, 3, 4]
2. sort() method:
• The sort() method is used to sort the elements of a list in ascending order by default.
• It modifies the list in place and does not return any value.
Example using sort() method:
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5] # Sort the list in ascending order my_list.sort() print("Sorted list in
ascending order:", my_list) # Output: Sorted list in ascending order: [1, 1, 2, 3, 4, 5, 5, 6, 9] # Sort the list in
descending order my_list.sort(reverse=True) print("Sorted list in descending order:", my_list) # Output:
Sorted list in descending order: [9, 6, 5, 5, 4, 3, 2, 1, 1]
In summary:
• pop() method removes and returns the element at a specified index from a list.
• sort() method sorts the elements of a list in ascending order by default, and it can be used to sort in
descending order by passing the reverse=True argument. Both methods modify the list in place.