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.
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.
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.
The document discusses Python lists, tuples, and dictionaries. It covers accessing and updating values in lists and tuples, deleting lists and tuples, and various built-in functions for lists, tuples, and dictionaries such as len(), max(), min(), etc. Methods for lists, tuples, and dictionaries are also explained, such as list.append(), tuple.count(), dict.clear(), etc. The key differences between lists, tuples, and dictionaries are that lists are mutable, tuples are immutable but can be concatenated, and dictionaries have unique keys.
The document discusses different Python data types including lists, tuples, and dictionaries. It provides information on how to create, access, modify, and delete items from each data type. For lists, it covers indexing, slicing, and common list methods. For tuples, it discusses creation, concatenation, slicing, and built-in methods. For dictionaries, it explains how they are created as a collection of unique keys and values, and how to access, add, remove, and delete key-value pairs.
This document discusses tuples in Python. Some key points:
1. Tuples are immutable sequences that are similar to lists but defined using parentheses. They can contain heterogeneous elements and support indexing, slicing, and repetition operations.
2. Tuples can be created using parentheses or the tuple() function. They cannot be modified once created.
3. Common tuple operations include accessing elements, mathematical operations, sorting, and using tuples as dictionary keys due to their immutability.
4. The differences between tuples and lists are that tuples are immutable while lists are mutable, tuples use parentheses and lists use brackets, and tuples can be used as dictionary keys while lists cannot.
5. Tuples can be
Lists, tuples, and dictionaries are common data structures in Python. Lists are mutable sequences that are defined using square brackets. Tuples are immutable sequences defined using parentheses. Dictionaries store key-value pairs within curly braces, with unique keys. These data structures support operations like indexing, slicing, length checking, membership testing, and iteration.
This document discusses tuples and dictionaries in Python. Tuples are immutable sequences that are defined using parentheses, while dictionaries are mutable mappings that associate keys with values. The document provides examples of creating, accessing, iterating over, and modifying tuples and dictionaries using various built-in functions and methods. It also compares the differences between tuples, lists, and dictionaries.
Mohammad Hassan's document discusses various Python data structures including arrays, tuples, dictionaries, and exceptions. It provides examples of how to define, access, modify, and loop through each type of data structure. Key points covered include using arrays to store multiple values, defining empty and one-element tuples, accessing dictionary values by key, and modifying dictionary contents by adding or removing keys. The document also compares the differences between lists and tuples, and between tuples and dictionaries.
A tuple is an immutable ordered collection of elements in Python. It is defined using parentheses and its elements can be of different data types. Tuples are faster than lists for accessing elements but cannot be modified once created. Common tuple operations include accessing elements by index, counting elements, slicing tuples, finding the maximum/minimum value, and deleting the entire tuple.
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.
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 tuples in Python, including what tuples are, how to create and access them, built-in tuple methods like count() and index(), and the differences between tuples, lists, and dictionaries. Tuples are immutable sequences that are indexed and can contain mixed data types. Common tuple operations include accessing elements, checking if an item exists, finding length, and using built-in methods to count occurrences or find indices of values. Tuples cannot be modified but new tuples can be created from existing ones using operators like addition.
Tuples are immutable sequences like lists but cannot be modified after creation, making them useful for storing fixed data like dictionary keys; they are created using parentheses and accessed using indexes and slices like lists but elements cannot be added, removed, or reassigned. Dictionaries are mutable mappings of unique keys to values that provide fast lookup of values by key and can be used to represent polynomials by mapping powers to coefficients.
This document discusses tuples in Python. It begins with definitions of tuples, noting that they are ordered, indexed and immutable sequences. It then provides examples of creating tuples using parentheses or not, and explains that a single element tuple requires a trailing comma. The document discusses tuple operations like slicing, comparison, assignment and using tuples as function return values or dictionary keys. It also covers built-in tuple methods and functions.
• List is a collection, which is ordered and changeable. Allows duplicate members.
• Tuple is a collection, which is ordered and unchangeable. Allows duplicate members.
• Set is a collection, which is unordered and unindexed. No duplicate members.
• Dictionary is a collection, which is unordered, changeable and indexed. No duplicate members.
Explains how to create a List in Python. Explains various operations that can be performed on Lists. Discusses various List class methods that can be used to manipulate the Lists. Explains what is a Tuple how to create it and various function that can be used on Tuples. Explains difference between List and Tuple
Python Is Very most Important for Your Life Time.SravaniSravani53
Python Tuple is an immutable (unchangeable) collection of various data type elements. Tuples are used to keep a list of immutable Python objects. The tuple is similar to lists in that the value of the items placed in the list can be modified, however the tuple is immutable and its value cannot be changed.
This document discusses tuples in Python. It defines a tuple as a sequence of immutable values that are indexed numerically. Tuples can contain different data types and are created using parentheses. The document explains how to access tuple elements, check if an item exists in a tuple, find the length of a tuple, and use built-in tuple methods. It also compares the key differences between tuples, lists, and dictionaries in terms of mutability, syntax, and supported operations. Sample Python programs are provided to demonstrate common operations on tuples like creation, accessing elements, unpacking values, and adding/removing items.
The document discusses different Python data types including lists, tuples, and dictionaries. It provides information on how to create, access, modify, and delete items from each data type. For lists, it covers indexing, slicing, and common list methods. For tuples, it discusses creation, concatenation, slicing, and built-in methods. For dictionaries, it explains how they are created as a collection of unique keys and values, and how to access, add, remove, and delete key-value pairs.
This document discusses tuples in Python. Some key points:
1. Tuples are immutable sequences that are similar to lists but defined using parentheses. They can contain heterogeneous elements and support indexing, slicing, and repetition operations.
2. Tuples can be created using parentheses or the tuple() function. They cannot be modified once created.
3. Common tuple operations include accessing elements, mathematical operations, sorting, and using tuples as dictionary keys due to their immutability.
4. The differences between tuples and lists are that tuples are immutable while lists are mutable, tuples use parentheses and lists use brackets, and tuples can be used as dictionary keys while lists cannot.
5. Tuples can be
Lists, tuples, and dictionaries are common data structures in Python. Lists are mutable sequences that are defined using square brackets. Tuples are immutable sequences defined using parentheses. Dictionaries store key-value pairs within curly braces, with unique keys. These data structures support operations like indexing, slicing, length checking, membership testing, and iteration.
This document discusses tuples and dictionaries in Python. Tuples are immutable sequences that are defined using parentheses, while dictionaries are mutable mappings that associate keys with values. The document provides examples of creating, accessing, iterating over, and modifying tuples and dictionaries using various built-in functions and methods. It also compares the differences between tuples, lists, and dictionaries.
Mohammad Hassan's document discusses various Python data structures including arrays, tuples, dictionaries, and exceptions. It provides examples of how to define, access, modify, and loop through each type of data structure. Key points covered include using arrays to store multiple values, defining empty and one-element tuples, accessing dictionary values by key, and modifying dictionary contents by adding or removing keys. The document also compares the differences between lists and tuples, and between tuples and dictionaries.
A tuple is an immutable ordered collection of elements in Python. It is defined using parentheses and its elements can be of different data types. Tuples are faster than lists for accessing elements but cannot be modified once created. Common tuple operations include accessing elements by index, counting elements, slicing tuples, finding the maximum/minimum value, and deleting the entire tuple.
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.
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 tuples in Python, including what tuples are, how to create and access them, built-in tuple methods like count() and index(), and the differences between tuples, lists, and dictionaries. Tuples are immutable sequences that are indexed and can contain mixed data types. Common tuple operations include accessing elements, checking if an item exists, finding length, and using built-in methods to count occurrences or find indices of values. Tuples cannot be modified but new tuples can be created from existing ones using operators like addition.
Tuples are immutable sequences like lists but cannot be modified after creation, making them useful for storing fixed data like dictionary keys; they are created using parentheses and accessed using indexes and slices like lists but elements cannot be added, removed, or reassigned. Dictionaries are mutable mappings of unique keys to values that provide fast lookup of values by key and can be used to represent polynomials by mapping powers to coefficients.
This document discusses tuples in Python. It begins with definitions of tuples, noting that they are ordered, indexed and immutable sequences. It then provides examples of creating tuples using parentheses or not, and explains that a single element tuple requires a trailing comma. The document discusses tuple operations like slicing, comparison, assignment and using tuples as function return values or dictionary keys. It also covers built-in tuple methods and functions.
• List is a collection, which is ordered and changeable. Allows duplicate members.
• Tuple is a collection, which is ordered and unchangeable. Allows duplicate members.
• Set is a collection, which is unordered and unindexed. No duplicate members.
• Dictionary is a collection, which is unordered, changeable and indexed. No duplicate members.
Explains how to create a List in Python. Explains various operations that can be performed on Lists. Discusses various List class methods that can be used to manipulate the Lists. Explains what is a Tuple how to create it and various function that can be used on Tuples. Explains difference between List and Tuple
Python Is Very most Important for Your Life Time.SravaniSravani53
Python Tuple is an immutable (unchangeable) collection of various data type elements. Tuples are used to keep a list of immutable Python objects. The tuple is similar to lists in that the value of the items placed in the list can be modified, however the tuple is immutable and its value cannot be changed.
This document discusses tuples in Python. It defines a tuple as a sequence of immutable values that are indexed numerically. Tuples can contain different data types and are created using parentheses. The document explains how to access tuple elements, check if an item exists in a tuple, find the length of a tuple, and use built-in tuple methods. It also compares the key differences between tuples, lists, and dictionaries in terms of mutability, syntax, and supported operations. Sample Python programs are provided to demonstrate common operations on tuples like creation, accessing elements, unpacking values, and adding/removing items.
The document discusses key concepts in data warehouse architecture including:
1) The functions of data warehouse tools which extract, clean, transform, load, and refresh data from source systems.
2) Key terminologies like metadata, which provides information about the data warehouse contents, and dimensional modeling using facts, dimensions, and data cubes.
3) Common multidimensional data models like star schemas with a central fact table linked to dimension tables and snowflake schemas which further normalize dimension tables.
The document discusses the Data Mining Query Language (DMQL), which was proposed for the DBMiner data mining system. DMQL is based on SQL and allows users to define data mining tasks by specifying data warehouses, data marts, and types of knowledge to mine, such as characterization, discrimination, association, classification, and prediction. It also provides syntax for concept hierarchy specification to organize data attributes into different levels.
This document discusses stacks and queues as data structures. It begins with an overview of stacks, including their definition as a last-in, first-out abstract data type and common stack operations. Array implementation of stacks is described through examples of push and pop operations. The document also covers applications of stacks and different notation styles for arithmetic expressions. Next, queues are introduced as first-in, first-out data structures, with details on their array representation and operations like enqueue and dequeue. Implementation of queues using arrays and handling overflow/underflow conditions are explained.
Quicksort is a widely used sorting algorithm that follows the divide and conquer paradigm. It works by recursively choosing a pivot element in an array, partitioning the array such that all elements less than the pivot come before all elements greater than the pivot, and then applying the same approach recursively to the sub-arrays. This has the effect of sorting the array in place with each iteration reducing the problem size until the entire array is sorted. The document provides pseudocode to implement quicksort and explains the algorithm at a high level.
This document discusses the architecture of knowledge-based systems (KBS). It explains that a KBS contains a knowledge module called the knowledge base (KB) and a control module called the inference engine. The KB explicitly represents knowledge that can be easily updated by domain experts without programming expertise. A knowledge engineer acts as a liaison between domain experts and the computer implementation. Propositional logic is then introduced as a basic technique for representing knowledge in KBS. It represents statements as atomic or compound propositions connected by logical operators like negation, conjunction, disjunction, implication, and biconditional.
Knowledge representation techniques are used to store knowledge in artificial intelligence systems so they can understand the world and solve complex problems. There are several common techniques, including logic, rules, semantic networks, frames, and scripts. Ontological engineering is used to develop large, modular ontologies that represent complex domains and allow knowledge to be integrated and combined. For knowledge representation systems to be effective, they must adequately and efficiently represent, store, manipulate, and acquire new knowledge.
The document discusses various file allocation methods and disk scheduling algorithms. There are three main file allocation methods - contiguous allocation, linked allocation, and indexed allocation. Contiguous allocation suffers from fragmentation but allows fast sequential access. Linked allocation does not have external fragmentation but is slower. Indexed allocation supports direct access but has higher overhead. For disk scheduling, algorithms like FCFS, SSTF, SCAN, CSCAN, and LOOK are described. SSTF provides lowest seek time while SCAN and CSCAN have higher throughput but longer wait times.
This document discusses segmentation in operating systems. Segmentation divides memory into variable-sized segments rather than fixed pages. Each process is divided into segments like the main program, functions, variables, etc. There are two types of segmentation: virtual memory segmentation which loads segments non-contiguously and simple segmentation which loads all segments together at once but non-contiguously in memory. Segmentation uses a segment table to map the two-part logical address to the single physical address through looking up the segment base address.
This document discusses virtual memory and demand paging. It explains that virtual memory separates logical memory from physical memory, allowing for larger address spaces than physical memory. Demand paging brings pages into memory only when needed, reducing I/O and memory usage. When a page is accessed that is not in memory, a page fault occurs and the operating system handles bringing that page in from disk while selecting a page to replace using an algorithm like FIFO, LRU, or optimal.
A decision tree classifier is explained. Key points include:
- Nodes test attribute values, edges correspond to test outcomes, and leaves predict the class.
- Information gain measures how much a variable contributes to the classification.
- It is used to select the variable that best splits the data at each node, with the highest information gain splitting the root node.
- An example calculates information gain for road type, obstruction, and speed limit variables to classify car speed. Speed limit has the highest information gain of 1 and is used to build the decision tree.
The document discusses the Apriori algorithm for frequent itemset mining. It explains that the Apriori algorithm uses an iterative approach consisting of join and prune steps to discover frequent itemsets that occur together above a minimum support threshold. The algorithm first finds all frequent 1-itemsets, then generates and prunes longer candidate itemsets in each iteration until no further frequent itemsets are found.
The document discusses the key components of a big data architecture. It describes how a big data architecture is needed to handle large volumes of data from multiple sources that is too large for traditional databases. The architecture ingests data from various sources, stores it, enables both batch and real-time analysis, and delivers business insights to users. It also provides examples of Flipkart's data platform which includes components like an ingestion system, batch/streaming processing, and a messaging queue.
Human Anatomy and Physiology II Unit 3 B pharm Sem 2
Respiratory system
Anatomy of respiratory system with special reference to anatomy
of lungs, mechanism of respiration, regulation of respiration
Lung Volumes and capacities transport of respiratory gases,
artificial respiration, and resuscitation methods
Urinary system
Anatomy of urinary tract with special reference to anatomy of
kidney and nephrons, functions of kidney and urinary tract,
physiology of urine formation, micturition reflex and role of
kidneys in acid base balance, role of RAS in kidney and
disorders of kidney
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxArshad Shaikh
Diptera, commonly known as flies, is a large and diverse order of insects that includes mosquitoes, midges, gnats, and horseflies. Characterized by a single pair of wings (hindwings are modified into balancing organs called halteres), Diptera are found in almost every environment and play important roles in ecosystems as pollinators, decomposers, and food sources. Some species, however, are significant pests and disease vectors, transmitting diseases like malaria, dengue, and Zika virus.
RE-LIVE THE EUPHORIA!!!!
The Quiz club of PSGCAS brings to you a fun-filled breezy general quiz set from numismatics to sports to pop culture.
Re-live the Euphoria!!!
QM: Eiraiezhil R K,
BA Economics (2022-25),
The Quiz club of PSGCAS
Exploring Ocean Floor Features for Middle SchoolMarie
This 16 slide science reader is all about ocean floor features. It was made to use with middle school students.
You can download the PDF at thehomeschooldaily.com
Thanks! Marie
Rose Cultivation Practices by Kushal Lamichhane.pdfkushallamichhame
This includes the overall cultivation practices of Rose prepared by:
Kushal Lamichhane (AKL)
Instructor
Shree Gandhi Adarsha Secondary School
Kageshowri Manohara-09, Kathmandu, Nepal
Pests of Rice: Damage, Identification, Life history, and Management.pptxArshad Shaikh
Rice pests can significantly impact crop yield and quality. Major pests include the brown plant hopper (Nilaparvata lugens), which transmits viruses like rice ragged stunt and grassy stunt; the yellow stem borer (Scirpophaga incertulas), whose larvae bore into stems causing deadhearts and whiteheads; and leaf folders (Cnaphalocrocis medinalis), which feed on leaves reducing photosynthetic area. Other pests include rice weevils (Sitophilus oryzae) and gall midges (Orseolia oryzae). Effective management strategies are crucial to minimize losses.
Parenting Teens: Supporting Trust, resilience and independencePooky Knightsmith
For more information about my speaking and training work, visit: https://www.pookyknightsmith.com/speaking/
SESSION OVERVIEW:
Parenting Teens: Supporting Trust, Resilience & Independence
The teenage years bring new challenges—for teens and for you. In this practical session, we’ll explore how to support your teen through emotional ups and downs, growing independence, and the pressures of school and social life.
You’ll gain insights into the teenage brain and why boundary-pushing is part of healthy development, along with tools to keep communication open, build trust, and support emotional resilience. Expect honest ideas, relatable examples, and space to connect with other parents.
By the end of this session, you will:
• Understand how teenage brain development affects behaviour and emotions
• Learn ways to keep communication open and supportive
• Explore tools to help your teen manage stress and bounce back from setbacks
• Reflect on how to encourage independence while staying connected
• Discover simple strategies to support emotional wellbeing
• Share experiences and ideas with other parents
Unit- 4 Biostatistics & Research Methodology.pdfKRUTIKA CHANNE
Blocking and confounding (when a third variable, or confounder, influences both the exposure and the outcome) system for Two-level factorials (a type of experimental design where each factor (independent variable) is investigated at only two levels, typically denoted as "high" and "low" or "+1" and "-1")
Regression modeling (statistical model that estimates the relationship between one dependent variable and one or more independent variables using a line): Hypothesis testing in Simple and Multiple regression models
Introduction to Practical components of Industrial and Clinical Trials Problems: Statistical Analysis Using Excel, SPSS, MINITAB®️, DESIGN OF EXPERIMENTS, R - Online Statistical Software to Industrial and Clinical trial approach
*Order Hemiptera:*
Hemiptera, commonly known as true bugs, is a large and diverse order of insects that includes cicadas, aphids, leafhoppers, and shield bugs. Characterized by their piercing-sucking mouthparts, Hemiptera feed on plant sap, other insects, or small animals. Many species are significant pests, while others are beneficial predators.
*Order Neuroptera:*
Neuroptera, also known as net-winged insects, is an order of insects that includes lacewings, antlions, and owlflies. Characterized by their delicate, net-like wing venation and large, often prominent eyes, Neuroptera are predators that feed on other insects, playing an important role in biological control. Many species have aquatic larvae, adding to their ecological diversity.
How to Create an Event in Odoo 18 - Odoo 18 SlidesCeline George
Creating an event in Odoo 18 is a straightforward process that allows you to manage various aspects of your event efficiently.
Odoo 18 Events Module is a powerful tool for organizing and managing events of all sizes, from conferences and workshops to webinars and meetups.
How to Configure Vendor Management in Lunch App of Odoo 18Celine George
The Vendor management in the Lunch app of Odoo 18 is the central hub for managing all aspects of the restaurants or caterers that provide food for your employees.
How to Manage Upselling of Subscriptions in Odoo 18Celine George
Subscriptions in Odoo 18 are designed to auto-renew indefinitely, ensuring continuous service for customers. However, businesses often need flexibility to adjust pricing or quantities based on evolving customer needs.
How to Manage Upselling of Subscriptions in Odoo 18Celine George
Ad
Programming in Python Lists and its methods .ppt
1. 10. Python - Lists
• The list is a most versatile datatype available in Python, which
can be written as a list of comma-separated values (items)
between square brackets. Good thing about a list that items in
a list need not all have the same type:
• Creating a list is as simple as putting different comma-
separated values between squere brackets. For example:
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];
Like string indices, list indices start at 0, and lists can be sliced,
concatenated and so on.
2. Accessing Values in Lists:
• To access values in lists, use the square brackets for slicing
along with the index or indices to obtain value available at that
index:
• Example:
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
• This will produce following result:
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
3. Updating Lists:
• You can update single or multiple elements of lists by giving the
slice on the left-hand side of the assignment operator, and you
can add to elements in a list with the append() method:
• Example:
list1 = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list1[2];
list1[2] = 2001;
print "New value available at index 2 : "
print list1[2];
• This will produce following result:
Value available at index 2 :
1997
New value available at index 2 :
2001
4. Delete List Elements:
• To remove a list element, you can use either the del statement
if you know exactly which element(s) you are deleting or the
remove() method if you do not know.
• Example:
list1 = ['physics', 'chemistry', 1997, 2000];
print list1;
del list1[2];
print "After deleting value at index 2 : "
print list1;
• This will produce following result:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
5. Basic List Operations:
• Lists respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new
list, not a string.
• In fact, lists respond to all of the general sequence operations we used
on strings in the prior chapter :
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
6. Indexing, Slicing, and Matrixes:
• Because lists are sequences, indexing and slicing work the same way for
lists as they do for strings.
• Assuming following input:
L = ['spam', 'Spam', 'SPAM!']
Python Expression Results Description
L[2] 'SPAM!' Offsets start at zero
L[-2] 'Spam' Negative: count from
the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
7. Built-in List Functions & Methods:
SN Function with Description
1 cmp(list1, list2)
Compares elements of both lists.
2 len(list)
Gives the total length of the list.
3 max(list)
Returns item from the list with max value.
4 min(list)
Returns item from the list with min value.
5 list(seq)
Converts a tuple into list.
8. SN Methods with Description
1 list.append(obj)
Appends object obj to list
2 list.count(obj)
Returns count of how many times obj occurs in list
3 list.extend(seq)
Appends the contents of seq to list
4 list.index(obj)
Returns the lowest index in list that obj appears
5 list.insert(index, obj)
Inserts object obj into list at offset index
6 list.pop(obj=list[-1])
Removes and returns last object or obj from list
7 list.remove(obj)
Removes object obj from list
8 list.reverse()
Reverses objects of list in place
9 list.sort([func])
Sorts objects of list, use compare func if given
9. 11. Python - Tuples
• A tuple is a sequence of immutable Python objects. Tuples are sequences,
just like lists. The only difference is that tuples can't be changed ie. tuples
are immutable and tuples use parentheses and lists use square brackets.
• Creating a tuple is as simple as putting different comma-separated values
and optionally you can put these comma-separated values between
parentheses also. For example:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing:
tup1 = ();
To write a tuple containing a single value you have to include a comma, even
though there is only one value:
tup1 = (50,);
• Like string indices, tuple indices start at 0, and tuples can be sliced,
concatenated and so on.
10. Accessing Values in Tuples:
• To access values in tuple, use the square brackets for slicing
along with the index or indices to obtain value available at that
index:
• Example:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0]
print "tup2[1:5]: “, tup2[1:5]
• This will produce following result:
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
11. Updating Tuples:
• Tuples are immutable which means you cannot update them or
change values of tuple elements. But we able able to take
portions of an existing tuples to create a new tuples as follows:
• Example:
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
tup3 = tup1 + tup2;
print tup3;
This will produce following result:
(12, 34.56, 'abc', 'xyz')
12. Delete Tuple Elements:
• Removing individual tuple elements is not possible. There is, of
course, nothing wrong with putting together another tuple with
the undesired elements discarded.
• To explicitly remove an entire tuple, just use the del statement:
• Example:
tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : " print tup;
• This will produce following result.
('physics', 'chemistry', 1997, 2000)
After deleting tup : Traceback (most recent call
last): File "test.py", line 9, in <module> print
tup; NameError: name 'tup' is not defined
13. Basic Tuples Operations:
• Tuples respond to the + and * operators much like strings; they
mean concatenation and repetition here too, except that the
result is a new tuple, not a string.
• In fact, tuples respond to all of the general sequence
operations we used on strings in the prior chapter :
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
14. Indexing, Slicing, and Matrixes:
• Because tuples are sequences, indexing and slicing work the
same way for tuples as they do for strings.
• Assuming following input:
L = ('spam', 'Spam', 'SPAM!')
Python
Expression
Results Description
L[2] 'SPAM!' Offsets start at zero
L[-2] 'Spam' Negative: count from the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
15. No Enclosing Delimiters:
• Any set of multiple objects, comma-separated, written without
identifying symbols, i.e., brackets for lists, parentheses for
tuples, etc., default to tuples, as indicated in these short
examples:
print 'abc', -4.24e93, 18+6.6j, 'xyz';
u, v = 1, 2;
print "Value of u , v : ", u,v;
print var;
• This will reduce following result:
abc -4.24e+93 (18+6.6j) xyz
Value of u , v : 1 2
16. Built-in Tuple Functions:
SN Function with Description
1 cmp(tuple1, tuple2)
Compares elements of both tuples.
2 len(tuple)
Gives the total length of the tuple.
3 max(tuple)
Returns item from the tuple with max value.
4 min(tuple)
Returns item from the tuple with min value.
5 tuple(seq)
Converts a list into tuple.