UNIT-3 python and data structure alo.pptxharikahhy
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way.
Good to know
The most recent major version of Python is Python 3, which we shall be using in this tutorial. However, Python 2, although not being updated with anything other than security updates, is still quite popular.
In this tutorial Python will be written in a text editor. It is possible to write Python in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are particularly useful when managing larger collections of Python files.
Python Syntax compared to other programming languages
Python was designed for readability, and has some similarities to the English language with influence from mathematics.
Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose.
Python is an easy-to-learn, interpreted programming language used for web development, software development, data science and more. It can be installed on Windows, Mac OS and Linux systems. Key Python concepts include variables, data types like lists and tuples, and basic operations. Lists are mutable sequences that can be accessed using indexes and slices, while tuples are immutable sequences. Sets are unordered collections that do not allow duplicate elements.
Tuple assignment allows multiple variables to be assigned values from an iterable like a list or tuple in a single statement. This is more concise than separate assignments and avoids using a temporary variable. For example, to swap the values of variables a and b, tuple assignment can be used: a, b = b, a. The left side must contain the same number of variables as there are elements on the right, and each value is assigned to the corresponding variable from left to right. Tuple assignment is useful for unpacking elements like splitting a string into parts.
The document provides an overview of Python data structures, functions, and recursion. It outlines topics including lists, dictionaries, tuples, sets, functions, recursion, and common errors. The aim is to equip students with a strong foundation in Python programming with a focus on understanding and applying fundamental concepts through programming tasks and examples. Key data structures are explained, such as how to create, access, modify, and delete elements from lists and tuples. Functions are also covered, including defining functions, passing arguments, and common errors.
The document discusses lists, tuples, and dictionaries in Python. It provides examples and explanations of these core data types. Lists are ordered and mutable sequences enclosed in brackets. Tuples are ordered and immutable sequences enclosed in parentheses. Dictionaries store data as key-value pairs within curly braces. Common operations on each type like indexing, slicing, length, keys and values are described. Methods for modifying and traversing lists like append, pop, insert and sort are also outlined.
This document discusses lists, tuples, and sets in Python. It provides examples and explanations of common operations for each including:
- Accessing, modifying, adding, and removing elements from lists and tuples
- Built-in functions like len(), max(), min(), sorted() for lists, tuples, and sets
- Immutability of tuples versus mutability of lists
- Set operations like union(), intersection(), difference(), symmetric_difference()
fundamental of python --- vivek singh shekawatshekhawatasshp
# Fundamentals of Python: A Comprehensive Guide
Python is a versatile and powerful programming language that has gained immense popularity in recent years. Known for its simplicity and readability, Python is an ideal choice for beginners and experienced programmers alike. This comprehensive guide covers the fundamentals of Python, providing a solid foundation for anyone looking to learn this dynamic language.
## Introduction to Python
### What is Python?
Python is a high-level, interpreted programming language designed by Guido van Rossum and first released in 1991. Its design philosophy emphasizes code readability and simplicity, making it an excellent language for beginners. Python supports multiple programming paradigms, including procedural, object-oriented, and functional programming.
### Why Learn Python?
Python's popularity stems from its versatility and ease of use. Here are some key reasons to learn Python:
- **Simplicity**: Python's syntax is straightforward and easy to learn, making it accessible to beginners.
- **Versatility**: Python can be used for web development, data analysis, artificial intelligence, machine learning, automation, and more.
- **Community Support**: Python has a large and active community, providing a wealth of resources, libraries, and frameworks.
- **Job Market**: Python skills are in high demand, making it a valuable language to learn for career opportunities.
## Setting Up Python
### Installation
To start coding in Python, you need to install it on your computer. Python is available for various operating systems, including Windows, macOS, and Linux. Follow these steps to install Python:
1. **Download Python**: Visit the official Python website (https://www.python.org) and download the latest version of Python for your operating system.
2. **Run the Installer**: Follow the installation instructions specific to your operating system. Ensure you select the option to add Python to your system PATH during installation.
3. **Verify Installation**: Open a command prompt or terminal and type `python --version` to verify the installation. You should see the installed Python version displayed.
### Integrated Development Environment (IDE)
An Integrated Development Environment (IDE) enhances your coding experience by providing tools and features to write, debug, and manage code efficiently. Some popular Python IDEs include:
- **PyCharm**: A powerful IDE specifically for Python, offering advanced features for professional developers.
- **Visual Studio Code**: A lightweight, versatile code editor with excellent Python support through extensions.
- **Jupyter Notebook**: An interactive web-based environment, ideal for data analysis and visualization.
## Basic Syntax and Data Types
### Hello, World!
The traditional first program in any language is the "Hello, World!" program. In Python, this is straightforward:
```python
print("Hello, World!")
```
This document provides an overview of key Python concepts including types, sequences, lists, functions, and parameters. It discusses how Python is both strongly and dynamically typed. The main built-in sequences - lists, tuples, strings, and ranges - are described. Lists are covered in detail including construction, operations like indexing, slicing, and built-in methods. Finally, the document outlines the different types of function parameters - positional, keyword, and combining the two - and how to handle parameter collections using the * operator.
The Key Difference between a List and a Tuple. The main difference between lists and a tuples is the fact that lists are mutable whereas tuples are immutable. A mutable data type means that a python object of this type can be modified. Let's create a list and assign it to a variable.
This document provides an introduction to Python programming unit 2 which covers lists, tuples, and dictionaries. Lists allow ordered sets of values accessed by index and can be modified. Tuples are similar to lists but immutable. Dictionaries store elements as key-value pairs that can be accessed by key. Common operations for each include accessing elements, determining length, membership testing, slicing, and built-in methods. Tuples can group data and be used as return values or in nested structures. Dictionaries allow creation and modification of elements through operations and methods.
This document provides information about Python lists. Some key points:
- Lists can store multiple elements of any data type. They are versatile for working with multiple elements.
- Lists maintain element order and allow duplicate elements. Elements are accessed via indexes.
- Lists support operations like concatenation, membership testing, slicing, and methods to add/remove elements.
- Nested lists allow lists within lists, for representing matrices and other complex data structures.
This document provides an overview of Python data structures, focusing on lists and tuples. It discusses how lists and tuples store and organize data, how to define, access, update, and manipulate elements within lists and tuples using various Python functions and methods. Lists are described as mutable sequences that can contain elements of different data types, while tuples are described as immutable sequences. The document provides examples of using lists and tuples for tasks like stacks, queues, and storing records. It also covers list and tuple operations like slicing, filtering, mapping, and reducing.
Python _dataStructures_ List, Tuples, its functionsVidhyaB10
Is a group of data elements that are put together
under one name
Defines a particular way of storing and organizing
data in a computer so that it can be used efficiently
List
Tuples
Lists and tuples are the main data types used to store multiple values in Python. Lists are ordered and changeable, while tuples are ordered and unchangeable. Some key differences are that lists use brackets and allow indexing, slicing, changing values, and other mutable operations, while tuples use parentheses and do not support mutable operations since values cannot be changed. Both support functions like append, length, checking for membership, and looping through values.
This document discusses lists in Python. It defines lists as mutable sequences that can contain elements of different types. Lists can be nested within other lists. Common list operations include accessing elements by index, slicing lists, modifying lists by assigning to indices, and using list methods like append(), pop(), sort(), and len(). The document provides examples of creating, accessing, modifying, and traversing lists in Python code.
The document discusses Python lists, which are the most basic data structure in Python. Lists allow storing multiple elements of different data types. Elements within lists can be accessed using indexes and slices, and lists support operations like concatenation, repetition, membership testing, and iteration. The document covers how to create, access, update, delete elements in lists, as well as built-in list functions and methods.
This document discusses Python lists and their uses. Lists are a mutable data type that allows storing multiple values in a single variable. Values in a list can be accessed by index and lists can be sliced, concatenated, and modified using built-in methods. Lists are commonly used with for loops to iterate over elements. Strings can be split into lists of substrings using the split() method.
The document discusses container data types in Python, including lists, tuples, sets, and dictionaries.
Lists allow indexing, slicing, and various methods like append(), insert(), pop(), and sort(). Tuples are like lists but immutable, and have methods like count(), index(), and tuple comprehension. Sets store unique elements and support operations like union and intersection. Dictionaries map keys to values and allow accessing elements via keys along with functions like get() and update().
This document discusses lists, tuples, and sets in Python. It provides examples and explanations of common operations for each including:
- Accessing, modifying, adding, and removing elements from lists and tuples
- Built-in functions like len(), max(), min(), sorted() for lists, tuples, and sets
- Immutability of tuples versus mutability of lists
- Set operations like union(), intersection(), difference(), symmetric_difference()
fundamental of python --- vivek singh shekawatshekhawatasshp
# Fundamentals of Python: A Comprehensive Guide
Python is a versatile and powerful programming language that has gained immense popularity in recent years. Known for its simplicity and readability, Python is an ideal choice for beginners and experienced programmers alike. This comprehensive guide covers the fundamentals of Python, providing a solid foundation for anyone looking to learn this dynamic language.
## Introduction to Python
### What is Python?
Python is a high-level, interpreted programming language designed by Guido van Rossum and first released in 1991. Its design philosophy emphasizes code readability and simplicity, making it an excellent language for beginners. Python supports multiple programming paradigms, including procedural, object-oriented, and functional programming.
### Why Learn Python?
Python's popularity stems from its versatility and ease of use. Here are some key reasons to learn Python:
- **Simplicity**: Python's syntax is straightforward and easy to learn, making it accessible to beginners.
- **Versatility**: Python can be used for web development, data analysis, artificial intelligence, machine learning, automation, and more.
- **Community Support**: Python has a large and active community, providing a wealth of resources, libraries, and frameworks.
- **Job Market**: Python skills are in high demand, making it a valuable language to learn for career opportunities.
## Setting Up Python
### Installation
To start coding in Python, you need to install it on your computer. Python is available for various operating systems, including Windows, macOS, and Linux. Follow these steps to install Python:
1. **Download Python**: Visit the official Python website (https://www.python.org) and download the latest version of Python for your operating system.
2. **Run the Installer**: Follow the installation instructions specific to your operating system. Ensure you select the option to add Python to your system PATH during installation.
3. **Verify Installation**: Open a command prompt or terminal and type `python --version` to verify the installation. You should see the installed Python version displayed.
### Integrated Development Environment (IDE)
An Integrated Development Environment (IDE) enhances your coding experience by providing tools and features to write, debug, and manage code efficiently. Some popular Python IDEs include:
- **PyCharm**: A powerful IDE specifically for Python, offering advanced features for professional developers.
- **Visual Studio Code**: A lightweight, versatile code editor with excellent Python support through extensions.
- **Jupyter Notebook**: An interactive web-based environment, ideal for data analysis and visualization.
## Basic Syntax and Data Types
### Hello, World!
The traditional first program in any language is the "Hello, World!" program. In Python, this is straightforward:
```python
print("Hello, World!")
```
This document provides an overview of key Python concepts including types, sequences, lists, functions, and parameters. It discusses how Python is both strongly and dynamically typed. The main built-in sequences - lists, tuples, strings, and ranges - are described. Lists are covered in detail including construction, operations like indexing, slicing, and built-in methods. Finally, the document outlines the different types of function parameters - positional, keyword, and combining the two - and how to handle parameter collections using the * operator.
The Key Difference between a List and a Tuple. The main difference between lists and a tuples is the fact that lists are mutable whereas tuples are immutable. A mutable data type means that a python object of this type can be modified. Let's create a list and assign it to a variable.
This document provides an introduction to Python programming unit 2 which covers lists, tuples, and dictionaries. Lists allow ordered sets of values accessed by index and can be modified. Tuples are similar to lists but immutable. Dictionaries store elements as key-value pairs that can be accessed by key. Common operations for each include accessing elements, determining length, membership testing, slicing, and built-in methods. Tuples can group data and be used as return values or in nested structures. Dictionaries allow creation and modification of elements through operations and methods.
This document provides information about Python lists. Some key points:
- Lists can store multiple elements of any data type. They are versatile for working with multiple elements.
- Lists maintain element order and allow duplicate elements. Elements are accessed via indexes.
- Lists support operations like concatenation, membership testing, slicing, and methods to add/remove elements.
- Nested lists allow lists within lists, for representing matrices and other complex data structures.
This document provides an overview of Python data structures, focusing on lists and tuples. It discusses how lists and tuples store and organize data, how to define, access, update, and manipulate elements within lists and tuples using various Python functions and methods. Lists are described as mutable sequences that can contain elements of different data types, while tuples are described as immutable sequences. The document provides examples of using lists and tuples for tasks like stacks, queues, and storing records. It also covers list and tuple operations like slicing, filtering, mapping, and reducing.
Python _dataStructures_ List, Tuples, its functionsVidhyaB10
Is a group of data elements that are put together
under one name
Defines a particular way of storing and organizing
data in a computer so that it can be used efficiently
List
Tuples
Lists and tuples are the main data types used to store multiple values in Python. Lists are ordered and changeable, while tuples are ordered and unchangeable. Some key differences are that lists use brackets and allow indexing, slicing, changing values, and other mutable operations, while tuples use parentheses and do not support mutable operations since values cannot be changed. Both support functions like append, length, checking for membership, and looping through values.
This document discusses lists in Python. It defines lists as mutable sequences that can contain elements of different types. Lists can be nested within other lists. Common list operations include accessing elements by index, slicing lists, modifying lists by assigning to indices, and using list methods like append(), pop(), sort(), and len(). The document provides examples of creating, accessing, modifying, and traversing lists in Python code.
The document discusses Python lists, which are the most basic data structure in Python. Lists allow storing multiple elements of different data types. Elements within lists can be accessed using indexes and slices, and lists support operations like concatenation, repetition, membership testing, and iteration. The document covers how to create, access, update, delete elements in lists, as well as built-in list functions and methods.
This document discusses Python lists and their uses. Lists are a mutable data type that allows storing multiple values in a single variable. Values in a list can be accessed by index and lists can be sliced, concatenated, and modified using built-in methods. Lists are commonly used with for loops to iterate over elements. Strings can be split into lists of substrings using the split() method.
The document discusses container data types in Python, including lists, tuples, sets, and dictionaries.
Lists allow indexing, slicing, and various methods like append(), insert(), pop(), and sort(). Tuples are like lists but immutable, and have methods like count(), index(), and tuple comprehension. Sets store unique elements and support operations like union and intersection. Dictionaries map keys to values and allow accessing elements via keys along with functions like get() and update().
First Review PPT gfinal gyft ftu liu yrfut goSowndarya6
CyberShieldX provides end-to-end security solutions, including vulnerability assessment, penetration testing, and real-time threat detection for business websites. It ensures that organizations can identify and mitigate security risks before exploitation.
Unlike traditional security tools, CyberShieldX integrates AI models to automate vulnerability detection, minimize false positives, and enhance threat intelligence. This reduces manual effort and improves security accuracy.
Many small and medium businesses lack dedicated cybersecurity teams. CyberShieldX provides an easy-to-use platform with AI-powered insights to assist non-experts in securing their websites.
Traditional enterprise security solutions are often expensive. CyberShieldX, as a SaaS platform, offers cost-effective security solutions with flexible pricing for businesses of all sizes.
Businesses must comply with security regulations, and failure to do so can result in fines or data breaches. CyberShieldX helps organizations meet compliance requirements efficiently.
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...ijscai
International Journal on Soft Computing, Artificial Intelligence and Applications (IJSCAI) is an open access peer-reviewed journal that provides an excellent international forum for sharing knowledge and results in theory, methodology and applications of Artificial Intelligence, Soft Computing. The Journal looks for significant contributions to all major fields of the Artificial Intelligence, Soft Computing in theoretical and practical aspects. The aim of the Journal is to provide a platform to the researchers and practitioners from both academia as well as industry to meet and share cutting-edge development in the field.
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...ijfcstjournal
One of the major challenges for software, nowadays, is software cost estimation. It refers to estimating the
cost of all activities including software development, design, supervision, maintenance and so on. Accurate
cost-estimation of software projects optimizes the internal and external processes, staff works, efforts and
the overheads to be coordinated with one another. In the management software projects, estimation must
be taken into account so that reduces costs, timing and possible risks to avoid project failure. In this paper,
a decision- support system using a combination of multi-layer artificial neural network and decision tree is
proposed to estimate the cost of software projects. In the model included into the proposed system,
normalizing factors, which is vital in evaluating efforts and costs estimation, is carried out using C4.5
decision tree. Moreover, testing and training factors are done by multi-layer artificial neural network and
the most optimal values are allocated to them. The experimental results and evaluations on Dataset
NASA60 show that the proposed system has less amount of the total average relative error compared with
COCOMO model.
May 2025: Top 10 Read Articles Advanced Information Technologyijait
International journal of advanced Information technology (IJAIT) is a bi monthly open access peer-reviewed journal, will act as a major forum for the presentation of innovative ideas, approaches, developments, and research projects in the area advanced information technology applications and services. It will also serve to facilitate the exchange of information between researchers and industry professionals to discuss the latest issues and advancement in the area of advanced IT. Core areas of advanced IT and multi-disciplinary and its applications will be covered during the conferences.
本資料「To CoT or not to CoT?」では、大規模言語モデルにおけるChain of Thought(CoT)プロンプトの効果について詳しく解説しています。
CoTはあらゆるタスクに効く万能な手法ではなく、特に数学的・論理的・アルゴリズム的な推論を伴う課題で高い効果を発揮することが実験から示されています。
一方で、常識や一般知識を問う問題に対しては効果が限定的であることも明らかになりました。
複雑な問題を段階的に分解・実行する「計画と実行」のプロセスにおいて、CoTの強みが活かされる点も注目ポイントです。
This presentation explores when Chain of Thought (CoT) prompting is truly effective in large language models.
The findings show that CoT significantly improves performance on tasks involving mathematical or logical reasoning, while its impact is limited on general knowledge or commonsense tasks.
A substation at an airport is a vital infrastructure component that ensures reliable and efficient power distribution for all airport operations. It acts as a crucial link, converting high-voltage electricity from the main grid to the lower voltages needed for various airport facilities. This essay will explore the functions, components, and importance of a substation at an airport.
Functions of an Airport Substation:
Voltage Conversion:
Substations step down high-voltage electricity to lower levels suitable for airport operations, like terminal buildings, runways, and other facilities.
Power Distribution:
They distribute electricity to various loads, including lighting, air conditioning, navigation systems, and ground support equipment.
Grid Stability:
Substations help maintain the stability of the power grid by controlling voltage levels and managing power flows.
Redundancy and Reliability:
Airports often have redundant substations or interconnected systems to ensure uninterrupted power supply, even in case of a fault.
Switching and Control:
Substations provide switching capabilities to connect or disconnect circuits, enabling maintenance and power management.
Protection:
Substations incorporate protective devices, like circuit breakers and relays, to safeguard the power system from faults and ensure safe operation.
Key Components of an Airport Substation:
Transformers: These convert high-voltage electricity to lower voltage levels.
Circuit Breakers: These devices switch circuits on or off, protecting the system from faults.
Busbars: These are large, conductive bars that distribute electricity from transformers to other equipment.
Switchgear: This includes equipment that controls the flow of electricity, such as isolators and switches.
Control and Protection Systems: These systems monitor the substation's performance, detect faults, and automatically initiate corrective actions.
Capacitors: These improve the power factor and reduce losses in the system.
Importance of Airport Substations:
Reliable Power Supply:
Substations are essential for providing reliable power to critical airport functions, ensuring safety and efficiency.
Safe and Efficient Operations:
They contribute to the safe and efficient operation of runways, terminals, and other airport facilities.
Airport Infrastructure:
Substations are an integral part of the airport's infrastructure, enabling various operations and services.
Economic Impact:
Substations support the economic activities of the airport, including passenger and cargo handling.
Modernization and Sustainability:
Modern substations incorporate advanced technologies and systems to improve efficiency, reduce energy consumption, and enhance sustainability.
In conclusion, an airport substation is a crucial component of airport infrastructure, ensuring reliable and efficient power distribution, grid stability, and safe operations.
This study will provide the audience with an understanding of the capabilities of soft tools such as Artificial Neural Networks (ANN), Support Vector Regression (SVR), Model Trees (MT), and Multi-Gene Genetic Programming (MGGP) as a statistical downscaling tool. Many projects are underway around the world to downscale the data from Global Climate Models (GCM). The majority of the statistical tools have a lengthy downscaling pipeline to follow. To improve its accuracy, the GCM data is re-gridded according to the grid points of the observed data, standardized, and, sometimes, bias-removal is required. The current work suggests that future precipitation can be predicted by using precipitation data from the nearest four grid points as input to soft tools and observed precipitation as output. This research aims to estimate precipitation trends in the near future (2021-2050), using 5 GCMs, for Pune, in the state of Maharashtra, India. The findings indicate that each one of the soft tools can model the precipitation with excellent accuracy as compared to the traditional method of Distribution Based Scaling (DBS). The results show that ANN models appear to give the best results, followed by MT, then MGGP, and finally SVR. This work is one of a kind in that it provides insights into the changing monsoon season in Pune. The anticipated average precipitation levels depict a rise of 300–500% in January, along with increases of 200-300% in February and March, and a 100-150% increase for April and December. In contrast, rainfall appears to be decreasing by 20-30% between June and September.
How Binning Affects LED Performance & Consistency.pdfMina Anis
🔍 What’s Inside:
📦 What Is LED Binning?
• The process of sorting LEDs by color temperature, brightness, voltage, and CRI
• Ensures visual and performance consistency across large installations
🎨 Why It Matters:
• Inconsistent binning leads to uneven color and brightness
• Impacts brand perception, customer satisfaction, and warranty claims
📊 Key Concepts Explained:
• SDCM (Standard Deviation of Color Matching)
• Recommended bin tolerances by application (e.g., 1–3 SDCM for retail/museums)
• How to read bin codes from LED datasheets
• The difference between ANSI/NEMA standards and proprietary bin maps
🧠 Advanced Practices:
• AI-assisted bin prediction
• Color blending and dynamic calibration
• Customized binning for high-end or global projects
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSsamueljackson3773
In this paper, the author discusses the concerns of using various wireless communications and how to use
them safely. The author also discusses the future of the wireless industry, wireless communication
security, protection methods, and techniques that could help organizations establish a secure wireless
connection with their employees. The author also discusses other essential factors to learn and note when
manufacturing, selling, or using wireless networks and wireless communication systems.
This document provides information about the Fifth edition of the magazine "Sthapatya" published by the Association of Civil Engineers (Practicing) Aurangabad. It includes messages from current and past presidents of ACEP, memories and photos from past ACEP events, information on life time achievement awards given by ACEP, and a technical article on concrete maintenance, repairs and strengthening. The document highlights activities of ACEP and provides a technical educational article for members.
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
1. 1
Online Workshop on ‘How to develop
Pythonic coding rather than Python
coding – Logic Perspective’
22.7.20 Day2 session 1
Dr. S.Mohideen Badhusha
Sr.Professor/ CSE department
Alva’s Institute Engineering and
Technology
Mijar, Moodbidri, Mangalore
3. 3
Objectives of the Day 2 session 1
To acquire a basic knowledge in List and Tuple
To comprehend the in-built functions and
operations in List and Tuple
To practice the simple programs in List and Tuple
To introduce the Pythonic way of writing the code
4. 4
Python offers a range of compound data types often
referred to as sequences.
List is one of the most frequently used and very
versatile datatypes used in Python.
Mutable object is the one which can be modified
Mutable ordered sequence of items of mixed types
How to create a list?
Ex: L=[1,2,3,4,5]
It can have any number of items and they may be of
different types (integer, float, string etc.).
5. 5
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
Also, a list can even have another list as an item. This is
called nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
6. 6
List Index
my_list = ['p','r','o','b','e']
print(my_list[0])
# Output: p
print(my_list[2])
# Output: o
print(my_list[4])
# Output: e
# my_list[4.0]
# Error! Only integer can be used for indexing
# Nested List
n_list = ["Happy", [2,0,1,5]]
# Nested indexing
print(n_list[0][1])
# Output: a
print(n_list[1][3])
# Output: 5
7. 7
Negative indexing
Python allows negative indexing for its sequences. The
index of -1 refers to the last item, -2 to the second last
item and so on.
my_list = ['p','r','o','b','e']
print(my_list[-1])
# Output: e
print(my_list[-5])
# Output: p
12. 12
Summary of List Functions
Append()- Add an element into list
extend()- Add all elements of a list to the another list
Insert() - Insert an item at the defined index
Remove()- removes an item from the list
Pop()- removes and returns an element at the given index
Clear()- removes all items from the list
Index()- returns the index of the first matched item
Count()- returns the count of number of items passed as an
argument
13. 13
Built-in List Functions
SN
Function with Description
1 len(list)-Gives the total length of the list.
2 max(list)-Returns item from the list with max value.
3 min(list)-Returns item from the list with min value.
4 list(seq)-Converts a tuple into list.
5 sum(list)-Adds the all the elements in the list (elements
should be numerical)
15. 15
Basic List Operations:
Lists respond to the + and * operators much like
strings; .
In fact, lists respond to all of the general sequence
operations we used on strings
Python
Expression
Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5,
6]
[1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!',
'Hi!']
Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]:
print x,
1 2 3 Iteration
16. 16
List Comprehension
List comprehension consists of an expression
followed by for statement inside square brackets.
pow2 = [2 ** x for x in range(10)]
# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
print(pow2)
This code is equivalent to the following codes
pow2 = []
for x in range(10):
pow2.append(2 ** x)
17. 17
pow2 = [2 ** x for x in range(10) if x > 5]
print(pow2)
#output : [64, 128, 256, 512]
odd = [x for x in range(20) if x % 2 == 1]
print(odd)
#output : [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
my_list = ['p','r','o','b','l','e','m']
print('p' in my_list)
# Output: True
print('a' in my_list)
# Output: False
print('c' not in my_list)
# Output: True
18. 18
What is tuple?
In Python programming, a tuple is similar to a list.
The difference between the two is that we cannot
change the elements of a tuple once it is assigned
whereas in a list, elements can be changed.
A simple immutable ordered sequence of items
Items can be of mixed types, including collection
types
immutable object is the one which can not be
modified
listlist
19. 19
Sequence Types
1. Tuple
A simple immutable ordered sequence of items
Items can be of mixed types, including collection types
1. Strings
– Immutable object is the one which can not be modified
– Conceptually very much like a tuple
2. List
Mutable object is the one which can be modified
Mutable ordered sequence of items of mixed types
20. 20
Similar Syntax
• All three sequence types (tuples, strings,
and lists) share much of the same syntax
and functionalities.
• Key difference:
– Tuples and strings are immutable
– Lists are mutable
• The operations shown in this section can be
applied to all sequence types
– most examples will just show the operation
performed on one
21. 21
Lists: Mutable
>>> li = [‘abc’, 23, 4.34, 23]
>>> li[1] = 45
>>> li
[‘abc’, 45, 4.34, 23]
• We can change lists in place.
• Name li still points to the same memory reference when
we’re done.
22. 22
Tuples: Immutable
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> t[2] = 3.14
Traceback (most recent call last):
File "<pyshell#75>", line 1, in -toplevel-
tu[2] = 3.14
TypeError: object doesn't support item assignment
You can’t change a tuple.
You can make a fresh tuple and assign its reference to a previously
used name.
>>> t = (23, ‘abc’, 3.14, (2,3), ‘def’)
23. 23
Sequence structures
• Tuples are defined using parentheses (and commas).
>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)
• Lists are defined using square brackets (and commas).
>>> li = [“abc”, 34, 4.34, 23]
• Strings are defined using quotes (“, ‘, or “““).
>>> st = “Hello World”
>>> st = ‘Hello World’
>>> st = “““This is a multi-line
string that uses triple quotes.”””
24. 24
Sequence access
• We can access individual members of a tuple, list, or string
using square bracket “array” notation.
>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> tu[1] # Second item in the tuple.
‘abc’
>>> li = [“abc”, 34, 4.34, 23]
>>> li[1] # Second item in the list.
34
>>> st = “Hello World”
>>> st[1] # Second character in string.
‘e’
25. 25
Positive and negative indices
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
Positive index: count from the left, starting with 0.
>>> t[1]
‘abc’
Negative lookup: count from right, starting with –1.
>>> t[-3]
4.56
26. 26
Slicing Operations
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
Return a copy of the container with a subset of the original
members. Start copying at the first index, and stop copying
before the second index.
>>> t[1:4]
(‘abc’, 4.56, (2,3))
You can also use negative indices when slicing.
>>> t[1:-1]
(‘abc’, 4.56, (2,3))
27. 27
Slicing Operations
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
Omit the first index to make a copy starting from the
beginning of the container.
>>> t[:2]
(23, ‘abc’)
Omit the second index to make a copy starting at the first
index and going to the end of the container.
>>> t[2:]
(4.56, (2,3), ‘def’)
28. 28
The ‘in’ Operator
• Boolean test whether a value is inside a container:
>>> t = [1, 2, 4, 5]
>>> 3 in t
False
>>> 4 in t
True
>>> 4 not in t
False
• For strings, tests for substrings
>>> a = 'abcde'
>>> 'c' in a
True
>>> 'cd' in a
True
>>> 'ac' in a
False
• Be careful: the in keyword is also used in the syntax of
for loops and list comprehensions.
29. 29
The + Operator
• The + operator produces a new tuple, list, or string whose value is
the concatenation of its arguments.
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> “Hello” + “ ” + “World”
‘Hello World’
30. 30
The * Operator
• The * operator produces a new tuple, list, or string that
“repeats” the original content.
>>> (1, 2, 3) * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> “Hello” * 3
‘HelloHelloHello’
31. 31
Concluding Tips
List- mutable (changeable) Tuple – immutable
( unchangeable)
list with mixed datatypes my_list = [1, "Hello", 3.4]
List and Tuple starts with 0 index
Extend() - a list is to be included as elements
Append() - to be included as single element
+ is concatenation operator for list,tuple and string.