This document provides an overview of lists in Python. It defines lists as ordered, mutable sequences that can contain elements of different data types. Key features covered include: lists allow duplicates, are indexed and sliced, can be modified via assignment, support common operations like membership testing and iteration. Examples are provided for list construction, accessing/replacing items by index, slicing subsets, checking if an item exists, and looping through lists.
This document provides an overview of Python data structures including lists, tuples, dictionaries, and sets. It discusses common list methods like append(), insert(), remove(), and sort(). It provides examples of using lists as stacks and queues. It also covers list comprehensions, the del statement, tuple packing and unpacking, set operations, looping through dictionaries, and comparing sequences.
در این جلسه از کلاس به ساختار های داده
Set, Tuple, Dictionary
پرداختیم
PySec101 Fall 2013 J3E1 By Mohammad Reza Kamalifard
Talk About :
Sets,Tuples and Dictionary Data Types in Python
This document provides examples and explanations for various Underscore.js methods for working with collections and arrays. It demonstrates methods for mapping, reducing, finding values, filtering, rejecting values, checking for values, sorting, grouping, sampling, partitioning, accessing elements, comparing values, and generating ranges.
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of WranglingPlotly
If you are struggling to make a plot, tear yourself away from stackoverflow for a moment and ... take a hard look at your data. Is it really in the most favorable form for the task at hand? Time and time again I have found that my visualization struggles are really a symptom of unfinished data wrangling. R has long had excellent facilities for data aggregation or "split-apply-combine": split an object into pieces, compute on each piece, and glue the result back together again. Recent developments, especially in the purrr package, have made "split-apply-combine" even easier and more general. But this requires a certain comfort level with lists, especially with lists that are columns inside a data frame. This is unfamiliar to most of us. I give an overview of this set of problems and match them up with solutions based on grouped, nested, and split data frames.
This document provides examples of various BASH scripting concepts like arrays, command line arguments, loops, functions, conditionals, input/output etc. It contains 16 programs demonstrating features such as array manipulation, looping constructs, taking user input, reading/writing files and more. The programs are intended to help learn BASH scripting through examples.
The document discusses Ruby's % notation for string interpolation and formatting. It shows examples of %, %Q, %q, %w, %W, %r, %s, %x, and % notation and what they return. It also discusses substring matching, blocks and procs, tap, and multiple assignment in Ruby.
Elixir & Phoenix – fast, concurrent and explicitTobias Pfeiffer
Elixir and Phoenix are known for their speed, but that’s far from their only benefit. Elixir isn’t just a fast Ruby and Phoenix isn’t just Rails for Elixir. Through pattern matching, immutable data structures and new idioms your programs can not only become faster but more understandable and maintainable. This talk will take a look at what’s great, what you might miss and augment it with production experience and advice.
Elixir & Phoenix – fast, concurrent and explicitTobias Pfeiffer
Elixir and Phoenix are known for their speed, but that’s far from their only benefit. Elixir isn’t just a fast Ruby and Phoenix isn’t just Rails for Elixir. Through pattern matching, immutable data structures and new idioms your programs can not only become faster but more understandable and maintainable. This talk will take a look at what’s great, what you might miss and augment it with production experience and advice.
This document provides an overview of Python data structures including lists, tuples, dictionaries, and sets. It discusses common list methods like append(), insert(), remove(), and sort(). It provides examples of using lists as stacks and queues. It also covers list comprehensions, the del statement, tuple packing and unpacking, set operations, looping through dictionaries, and comparing sequences.
در این جلسه از کلاس به ساختار های داده
Set, Tuple, Dictionary
پرداختیم
PySec101 Fall 2013 J3E1 By Mohammad Reza Kamalifard
Talk About :
Sets,Tuples and Dictionary Data Types in Python
This document provides examples and explanations for various Underscore.js methods for working with collections and arrays. It demonstrates methods for mapping, reducing, finding values, filtering, rejecting values, checking for values, sorting, grouping, sampling, partitioning, accessing elements, comparing values, and generating ranges.
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of WranglingPlotly
If you are struggling to make a plot, tear yourself away from stackoverflow for a moment and ... take a hard look at your data. Is it really in the most favorable form for the task at hand? Time and time again I have found that my visualization struggles are really a symptom of unfinished data wrangling. R has long had excellent facilities for data aggregation or "split-apply-combine": split an object into pieces, compute on each piece, and glue the result back together again. Recent developments, especially in the purrr package, have made "split-apply-combine" even easier and more general. But this requires a certain comfort level with lists, especially with lists that are columns inside a data frame. This is unfamiliar to most of us. I give an overview of this set of problems and match them up with solutions based on grouped, nested, and split data frames.
This document provides examples of various BASH scripting concepts like arrays, command line arguments, loops, functions, conditionals, input/output etc. It contains 16 programs demonstrating features such as array manipulation, looping constructs, taking user input, reading/writing files and more. The programs are intended to help learn BASH scripting through examples.
The document discusses Ruby's % notation for string interpolation and formatting. It shows examples of %, %Q, %q, %w, %W, %r, %s, %x, and % notation and what they return. It also discusses substring matching, blocks and procs, tap, and multiple assignment in Ruby.
Elixir & Phoenix – fast, concurrent and explicitTobias Pfeiffer
Elixir and Phoenix are known for their speed, but that’s far from their only benefit. Elixir isn’t just a fast Ruby and Phoenix isn’t just Rails for Elixir. Through pattern matching, immutable data structures and new idioms your programs can not only become faster but more understandable and maintainable. This talk will take a look at what’s great, what you might miss and augment it with production experience and advice.
Elixir & Phoenix – fast, concurrent and explicitTobias Pfeiffer
Elixir and Phoenix are known for their speed, but that’s far from their only benefit. Elixir isn’t just a fast Ruby and Phoenix isn’t just Rails for Elixir. Through pattern matching, immutable data structures and new idioms your programs can not only become faster but more understandable and maintainable. This talk will take a look at what’s great, what you might miss and augment it with production experience and advice.
This document provides a 5 minute summary of key Python concepts including variables, data types, conditionals, loops, functions, classes and modules. It demonstrates how to define and use integers, floats, strings, booleans, lists, tuples, dictionaries and sets. It also shows the syntax for if/else statements, for/while loops, functions, lambda functions, classes and importing/using modules in Python.
This document discusses operations that can be performed on lists in Python. It covers copying lists, slicing lists to extract subsets, checking for elements in or not in lists, finding the maximum/minimum element or location of an element in a list, and deleting elements or slices from a list. Examples are provided for each operation to demonstrate how it works on sample lists.
This document provides an overview of selecting elements from lists and numpy arrays in Python. It demonstrates how to select a single element, slice a range of elements, select elements from nested lists and 2D numpy arrays. Various list and numpy array methods are also described, such as sorting, appending, inserting, deleting and calculating statistics.
The document discusses using Ruby to count URL access frequencies from a log file. It explains that the map function processes the log by outputting pairs of URLs and a count of 1. The reduce function then combines these pairs by adding the counts for the same URL, outputting pairs of URLs and total access counts. This is a common pattern in MapReduce programming where map generates key-value pairs that reduce then combines.
This document provides an overview of the Elixir programming language, including its history, key features and idioms, data types, functions, modules, and compilation process. Some key points covered include:
- Elixir was created to leverage the Erlang VM while adding features like metaprogramming, polymorphism, and better tooling.
- It supports highly concurrent, reliable applications through features like easy concurrency using the actor model, fault tolerance, immutability, and leveraging Erlang's legacy.
- Core data types include integers, floats, atoms, binaries, lists, tuples, maps, and structs. Functions, pattern matching, comprehensions, and named functions are also
The document discusses clustering and numpy arrays in Python. It shows how to create arrays using numpy, perform operations like summing and finding min/max values, and access elements and slices. It also introduces Cython and demonstrates compiling a simple "Hello World" Cython program and using Cython to optimize a Python prime number generation function for improved performance.
1. Closures allow functions to be passed as arguments to other functions and returned from functions. They capture any values from the context in which they are defined.
2. Common closure syntax includes defining parameter types, return types, and code blocks. Collection functions like map, filter, and reduce take closures as arguments to transform collections.
3. Swift provides syntactic sugar to simplify closure syntax by removing explicit types and parameter names like $0 and $1. Closures can be passed to methods to sort, filter, or transform collections.
Python an-intro youtube-livestream-day2MAHALAKSHMI P
Python an Introduction to List and Strings in English. This presentation has been prepared to take the class in live youtube stream https://youtu.be/-yrO0bOBwsY
The document discusses the deque collection in Python. Some key points:
- Deque allows fast appends and pops from either side of the list, with O(1) time complexity, unlike regular lists which are slow (O(n)) for pop(0) and insert(0,v).
- Deque provides methods like append, appendleft, popleft, pop for adding/removing elements from either side of the list.
- It can be initialized with a maximum length to act as a sliding window, discarding old elements as new ones are added.
- Methods like rotate rotate the deque a given number of positions, extending adds multiple elements at once. Deque is useful when
The document provides instructions for using a Python library called "instructions" that allows searching and filtering data in Python containers using intuitive commands. It demonstrates finding all strings of length 3 in various nested containers, provides examples of other supported commands, and details features like advanced querying, installation, and supported datatypes.
This document provides an overview of Python collections including strings, bytes, lists, tuples, dictionaries, sets, and ranges. It discusses how to create, access, modify, iterate through, and perform common operations on each collection type. For each collection, it provides examples of basic usage and built-in methods. The document is intended as a reference for working with the main collection data types in Python.
The document provides information on arrays and hashes in Ruby. It discusses that arrays are ordered lists that can contain objects, and hashes are collections of key-value pairs. It then provides examples of creating, accessing, and modifying arrays and hashes. It also discusses various methods for iterating over arrays and hashes, such as each, collect, and each_pair.
Open course(programming languages) 20150121JangChulho
This document discusses programming language concepts like string manipulation, regular expressions, and finite state machines. It provides examples of using string methods like find, slice, and split to select substrings. It also demonstrates how to use regular expressions to search strings by matching patterns like numbers, letters, whitespace. Finally, it introduces finite state machines as a way to represent programs that take input strings and determine whether they match a pattern.
This document is a Python script that modifies map elements, extents, and scales in an ArcGIS map document based on user-specified parameters. It changes the map name, location, and classification text displayed on the layout. It can also set the map extent to the bounds of a nearest city or specific MGRS grid specified by the user. The script supports setting the map scale to preset or custom values defined by the user.
- R can be used as a calculator to perform basic math operations like addition, subtraction, multiplication, division, exponents, logarithms, and trigonometric functions. It handles complex numbers and vectors.
- Matrices can be created using cbind() and rbind() functions. Elements are extracted using row and column indices. Common operations include addition, subtraction, scalar and element-wise multiplication on matrices.
- Eigenvalues and eigenvectors of a matrix can be computed using the eigen() function. The uniroot() function finds the root of a univariate function by calling a user-defined function.
This document provides information about data structures in Python. It discusses lists, tuples, sets, and dictionaries. For lists and tuples, it covers defining, indexing, slicing, unpacking, methods, built-in functions, and list comprehensions. Lists can contain heterogeneous elements and support methods like append(), pop(), sort(), and reverse(). Tuples are similar to lists but are immutable ordered sequences. They also support indexing, slicing, and unpacking. This document serves as a guide to working with common Python data structures.
This presentation is all about various built in
datastructures which we have in python.
List
Dictionary
Tuple
Set
and various methods present in each data structure
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.
Lists allow storing and manipulating multiple values in a single variable. A list is a mutable collection that can hold elements of any type, accessed by index. Key characteristics of lists include: using square brackets to define lists; mutable elements that can be added, removed, or modified; built-in functions like len(), min(), max(), and sum(); slicing to extract portions; and splitting strings into lists of substrings. Lists are widely used in Python for tasks like collecting related data, looping through elements, and parsing structured data.
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.
This document provides an overview of Python data structures including lists, tuples, dictionaries, and sets. It discusses common list methods like append(), insert(), remove(), and sort(). It provides examples of using lists as stacks and queues. It also covers list comprehensions, the del statement, tuple packing and unpacking, set operations, looping through dictionaries, and comparing sequences.
This document provides a 5 minute summary of key Python concepts including variables, data types, conditionals, loops, functions, classes and modules. It demonstrates how to define and use integers, floats, strings, booleans, lists, tuples, dictionaries and sets. It also shows the syntax for if/else statements, for/while loops, functions, lambda functions, classes and importing/using modules in Python.
This document discusses operations that can be performed on lists in Python. It covers copying lists, slicing lists to extract subsets, checking for elements in or not in lists, finding the maximum/minimum element or location of an element in a list, and deleting elements or slices from a list. Examples are provided for each operation to demonstrate how it works on sample lists.
This document provides an overview of selecting elements from lists and numpy arrays in Python. It demonstrates how to select a single element, slice a range of elements, select elements from nested lists and 2D numpy arrays. Various list and numpy array methods are also described, such as sorting, appending, inserting, deleting and calculating statistics.
The document discusses using Ruby to count URL access frequencies from a log file. It explains that the map function processes the log by outputting pairs of URLs and a count of 1. The reduce function then combines these pairs by adding the counts for the same URL, outputting pairs of URLs and total access counts. This is a common pattern in MapReduce programming where map generates key-value pairs that reduce then combines.
This document provides an overview of the Elixir programming language, including its history, key features and idioms, data types, functions, modules, and compilation process. Some key points covered include:
- Elixir was created to leverage the Erlang VM while adding features like metaprogramming, polymorphism, and better tooling.
- It supports highly concurrent, reliable applications through features like easy concurrency using the actor model, fault tolerance, immutability, and leveraging Erlang's legacy.
- Core data types include integers, floats, atoms, binaries, lists, tuples, maps, and structs. Functions, pattern matching, comprehensions, and named functions are also
The document discusses clustering and numpy arrays in Python. It shows how to create arrays using numpy, perform operations like summing and finding min/max values, and access elements and slices. It also introduces Cython and demonstrates compiling a simple "Hello World" Cython program and using Cython to optimize a Python prime number generation function for improved performance.
1. Closures allow functions to be passed as arguments to other functions and returned from functions. They capture any values from the context in which they are defined.
2. Common closure syntax includes defining parameter types, return types, and code blocks. Collection functions like map, filter, and reduce take closures as arguments to transform collections.
3. Swift provides syntactic sugar to simplify closure syntax by removing explicit types and parameter names like $0 and $1. Closures can be passed to methods to sort, filter, or transform collections.
Python an-intro youtube-livestream-day2MAHALAKSHMI P
Python an Introduction to List and Strings in English. This presentation has been prepared to take the class in live youtube stream https://youtu.be/-yrO0bOBwsY
The document discusses the deque collection in Python. Some key points:
- Deque allows fast appends and pops from either side of the list, with O(1) time complexity, unlike regular lists which are slow (O(n)) for pop(0) and insert(0,v).
- Deque provides methods like append, appendleft, popleft, pop for adding/removing elements from either side of the list.
- It can be initialized with a maximum length to act as a sliding window, discarding old elements as new ones are added.
- Methods like rotate rotate the deque a given number of positions, extending adds multiple elements at once. Deque is useful when
The document provides instructions for using a Python library called "instructions" that allows searching and filtering data in Python containers using intuitive commands. It demonstrates finding all strings of length 3 in various nested containers, provides examples of other supported commands, and details features like advanced querying, installation, and supported datatypes.
This document provides an overview of Python collections including strings, bytes, lists, tuples, dictionaries, sets, and ranges. It discusses how to create, access, modify, iterate through, and perform common operations on each collection type. For each collection, it provides examples of basic usage and built-in methods. The document is intended as a reference for working with the main collection data types in Python.
The document provides information on arrays and hashes in Ruby. It discusses that arrays are ordered lists that can contain objects, and hashes are collections of key-value pairs. It then provides examples of creating, accessing, and modifying arrays and hashes. It also discusses various methods for iterating over arrays and hashes, such as each, collect, and each_pair.
Open course(programming languages) 20150121JangChulho
This document discusses programming language concepts like string manipulation, regular expressions, and finite state machines. It provides examples of using string methods like find, slice, and split to select substrings. It also demonstrates how to use regular expressions to search strings by matching patterns like numbers, letters, whitespace. Finally, it introduces finite state machines as a way to represent programs that take input strings and determine whether they match a pattern.
This document is a Python script that modifies map elements, extents, and scales in an ArcGIS map document based on user-specified parameters. It changes the map name, location, and classification text displayed on the layout. It can also set the map extent to the bounds of a nearest city or specific MGRS grid specified by the user. The script supports setting the map scale to preset or custom values defined by the user.
- R can be used as a calculator to perform basic math operations like addition, subtraction, multiplication, division, exponents, logarithms, and trigonometric functions. It handles complex numbers and vectors.
- Matrices can be created using cbind() and rbind() functions. Elements are extracted using row and column indices. Common operations include addition, subtraction, scalar and element-wise multiplication on matrices.
- Eigenvalues and eigenvectors of a matrix can be computed using the eigen() function. The uniroot() function finds the root of a univariate function by calling a user-defined function.
This document provides information about data structures in Python. It discusses lists, tuples, sets, and dictionaries. For lists and tuples, it covers defining, indexing, slicing, unpacking, methods, built-in functions, and list comprehensions. Lists can contain heterogeneous elements and support methods like append(), pop(), sort(), and reverse(). Tuples are similar to lists but are immutable ordered sequences. They also support indexing, slicing, and unpacking. This document serves as a guide to working with common Python data structures.
This presentation is all about various built in
datastructures which we have in python.
List
Dictionary
Tuple
Set
and various methods present in each data structure
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.
Lists allow storing and manipulating multiple values in a single variable. A list is a mutable collection that can hold elements of any type, accessed by index. Key characteristics of lists include: using square brackets to define lists; mutable elements that can be added, removed, or modified; built-in functions like len(), min(), max(), and sum(); slicing to extract portions; and splitting strings into lists of substrings. Lists are widely used in Python for tasks like collecting related data, looping through elements, and parsing structured data.
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.
This document provides an overview of Python data structures including lists, tuples, dictionaries, and sets. It discusses common list methods like append(), insert(), remove(), and sort(). It provides examples of using lists as stacks and queues. It also covers list comprehensions, the del statement, tuple packing and unpacking, set operations, looping through dictionaries, and comparing sequences.
This document provides an overview of Python data structures including lists, tuples, dictionaries, and sets. It discusses common list methods like append(), insert(), remove(), and sort(). It provides examples of using lists as stacks and queues. It also covers list comprehensions, the del statement, tuple packing and unpacking, set operations, looping through dictionaries, and comparing sequences.
This document provides an overview of Python data structures including lists, tuples, dictionaries, and sets. It discusses common list methods like append(), insert(), remove(), and sort(). It provides examples of using lists as stacks and queues. It also covers list comprehensions, the del statement, tuple packing and unpacking, set operations, looping through dictionaries, and comparing sequences.
This document provides an overview of Python data structures including lists, tuples, dictionaries, and sets. It discusses common list methods like append(), insert(), remove(), and sort(). It provides examples of using lists as stacks and queues. It also covers list comprehensions, the del statement, tuple packing and unpacking, set operations, looping through dictionaries, and comparing sequences.
This document provides an overview of Python data structures including lists, tuples, dictionaries, and sets. It discusses common list methods like append(), insert(), remove(), and sort(). It provides examples of using lists as stacks and queues. It also covers list comprehensions, the del statement, tuple packing and unpacking, set operations, looping through dictionaries, and comparing sequences.
This document provides an overview of lists in Python. It defines what a list is, how to create and access list elements, and common list operations like slicing, concatenation, and modification. It also covers list methods such as append(), insert(), remove(), and sort(). The document discusses lists as mutable objects and the concepts of aliasing and passing lists to functions.
This document discusses lists in Python. It defines lists as sequences that can contain elements of any type. Lists are created using square brackets and their elements can be accessed and modified using indices. Some key list methods mentioned include append(), sort(), and pop(). The document provides many examples of how to construct, access, modify, and perform common operations on lists in Python.
A dictionary is used to store player details like name, age, height and experience for a cricket team. Players under 19 are extracted to a new dictionary. 11 players are selected from the under 19 dictionary based on experience. The tallest player is chosen as the captain. The team and captain details are displayed.
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.
This document discusses strings, lists, tuples, and dictionaries in Python. It shows how to initialize and access elements in each of these data types. Strings can be initialized using single, double, or triple quotes. Lists store elements enclosed in square brackets and support indexing, slicing, concatenation, and other operations. Tuples are like lists but use parentheses; they are immutable. Dictionaries map keys to values using curly braces and colons. Elements in strings, lists, and tuples are accessed via integer indices, while dictionary items are accessed via their keys.
This document provides an overview of many common Python programming concepts including variables, strings, lists, tuples, dictionaries, conditionals, functions, classes, files and exceptions. It demonstrates how to store and manipulate different data types, write conditional logic, define reusable blocks of code as functions, organize code into classes and objects, read from and write to files, and handle errors through exceptions. Key examples include creating and accessing elements in lists and dictionaries, writing conditional statements, defining and calling functions, creating classes and using inheritance, opening and reading/writing files, and using try/except blocks to catch errors.
The document discusses lists in Python. Some key points:
- A list is a mutable ordered sequence of elements of any data type. Lists can be created using square brackets or the list() constructor.
- List elements can be accessed using indexes and sliced. Methods like append(), insert(), pop() etc. are used to modify lists.
- Lists support operations like membership testing, repetition, concatenation etc. Functions like len(), max(), min() etc. operate on lists.
- Lists can be passed to and returned from functions. List comprehension provides a concise way to create lists.
- Searching and sorting algorithms like linear search, binary search, bubble sort, selection sort can be
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()
Python 101++: Let's Get Down to Business!Paige Bailey
You've started the Codecademy and Coursera courses; you've thumbed through Zed Shaw's "Learn Python the Hard Way"; and now you're itching to see what Python can help you do. This is the workshop for you!
Here's the breakdown: we're going to be taking you on a whirlwind tour of Python's capabilities. By the end of the workshop, you should be able to easily follow any of the widely available Python courses on the internet, and have a grasp on some of the more complex aspects of the language.
Please don't forget to bring your personal laptop!
Audience: This course is aimed at those who already have some basic programming experience, either in Python or in another high level programming language (such as C/C++, Fortran, Java, Ruby, Perl, or Visual Basic). If you're an absolute beginner -- new to Python, and new to programming in general -- make sure to check out the "Python 101" workshop!
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
.
This document provides an overview of regular expressions in Python. It defines regular expressions as sequences of characters used to search for patterns in strings. The re module allows using regular expressions in Python programs. Metacharacters like [], ., ^, $, *, + extend the matching capabilities of regular expressions beyond basic text. Examples demonstrate using re functions like search and special characters to extract lines from files based on patterns.
The document discusses Python dictionaries. Some key points:
- A dictionary in Python is an unordered collection of key-value pairs where keys must be unique and immutable, while values can be any data type.
- Dictionaries are created using curly braces {} and keys are separated from values with colons.
- Elements can be accessed, added, updated, and deleted using keys. Nested dictionaries are also supported.
- Common operations include creating, accessing, modifying dictionaries as well as nested dictionaries. User input can also be used to update dictionary values.
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.
The document provides information about strings in Python. Some key points include:
- Strings are immutable sequences of characters that can be accessed using indexes. Common string methods allow operations like uppercase, lowercase, counting characters, etc.
- Strings support slicing to extract substrings, and various string formatting methods allow combining strings with variables or other strings.
- Loops can be used to iterate through strings and perform operations on individual characters. Built-in string methods do not modify the original string.
- Examples demonstrate various string operations like indexing, slicing, checking substrings, string methods, formatting and parsing strings. Loops are used to count characters in examples.
This document discusses file handling in Python. It begins by explaining that files allow permanent storage of data, unlike standard input/output which is volatile. It then covers opening files in different modes, reading files line-by-line or as a whole, and modifying the file pointer position using seek(). Key points include opening files returns a file object, reading can be done line-by-line with for loops or using read()/readlines(), and seek() allows changing the file pointer location.
Computer Communication Networks- Introduction to Transport layerKrishna Nanda
The document summarizes the key functions and services of the transport layer:
1) The transport layer provides process-to-process communication between applications on different hosts using addressing that identifies processes via port numbers in addition to IP addresses.
2) It implements services like multiplexing/demultiplexing, flow control, error control, and reliable data transfer to ensure reliable end-to-end delivery of data between applications.
3) Transport layer protocols encapsulate and decapsulate messages, adding headers that include sequence numbers and acknowledgments to implement functions like error detection and retransmission.
Computer Communication Networks- TRANSPORT LAYER PROTOCOLSKrishna Nanda
The document discusses transport layer protocols. It begins by explaining that the transport layer sits between the application and network layers, providing services to applications and receiving services from the network layer. It then notes that the three major transport layer protocols are UDP, TCP, and SCTP. UDP provides a simple, unreliable connectionless service. TCP provides a reliable, connection-oriented service through mechanisms like flow and error control. SCTP combines features of UDP and TCP, providing both connection-oriented and connectionless services.
The document discusses network layer protocols and IPv4 specifically. It provides three key points:
1) IPv4 is the main network layer protocol in the Internet that provides "best effort" delivery of packets called datagrams from source to destination through various networks in a connectionless manner.
2) IPv4 packets, or datagrams, contain a header with fields that provide routing information and a payload section for data. The header fields include source and destination addresses, identification information, flags for fragmentation, and more.
3) IPv4 supports fragmentation of large datagrams into smaller pieces to accommodate the size constraints of different networks. The fragmentation process and header fields related to fragmentation are described.
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2Krishna Nanda
The document discusses unicast routing protocols used in the Internet, focusing on the Routing Information Protocol (RIP). It provides details on:
1) How the Internet uses hierarchical routing with interior gateway protocols (IGPs) like RIP within autonomous systems (ASes) and exterior gateway protocols like BGP between ASes.
2) Key aspects of RIP including using hop count as the routing metric, periodic routing updates, timers that control route expiration and garbage collection, and its distance-vector algorithm.
3) RIP's scalability is limited by only allowing up to 15 hops within an AS, but it has simple message formats and local updating between neighboring routers.
Computer Communication Networks-Routing protocols 1Krishna Nanda
This document provides an overview of routing protocols in computer networks. It discusses:
1) The goal of routing is to deliver data packets from source to destination(s) using forwarding tables updated by routing protocols. Routing can be unicast (one-to-one) or multicast (one-to-many).
2) Common routing algorithms include distance-vector routing (Bellman-Ford algorithm) and link-state routing (Dijkstra's algorithm). Distance-vector routing uses distance vectors exchanged between neighbors to calculate least-cost paths.
3) Issues with distance-vector routing include slow convergence and counting to infinity when link costs increase.
Computer Communication Networks-Wireless LANKrishna Nanda
Wireless LANs allow hosts to connect to a network without being physically connected via cables. They use radio waves to transmit data through the air. Some key differences between wired and wireless LANs include the mobility of hosts in wireless LANs and the use of access points to connect wireless LANs to wired networks. Wireless LANs also face challenges from signal attenuation, interference, and multipath propagation that wired LANs do not. The IEEE 802.11 standard defines the specifications for wireless LANs, including using basic service sets and extended service sets to connect multiple wireless networks, and employing carrier sense multiple access with collision avoidance for medium access control.
Computer Communication Networks-Network LayerKrishna Nanda
The document discusses the network layer in computer networks. It describes that the network layer is responsible for packetizing data by encapsulating it and adding headers, routing packets from source to destination by determining the best path, and forwarding packets through routers along the path. It explains the two main approaches used at the network layer - connectionless datagram service where each packet is routed independently, and connection-oriented virtual circuit service where a connection is established and packets follow the same path.
This document provides an overview of arrays and strings in C programming. It discusses:
- Arrays can store a collection of like-typed data and each element is accessed via an index. Common array types include one-dimensional and multi-dimensional arrays.
- Strings in C are arrays of characters that are null-terminated. Functions like printf, scanf, gets and puts can be used to output and input strings.
- Linear and binary search algorithms are described for finding a value within an array. Sorting techniques like bubble, insertion and selection sorts are also mentioned.
Structures allow grouping of different data types under one name. A structure defines a template for storing multiple data items of different types together. Structure variables can then be declared based on this template to store actual data. Structure members are accessed using the dot operator. Arrays of structures can be used to store information about multiple objects of the same type. Structures can also be nested by defining a structure as a member of another structure. Structures can be passed to functions by value or by reference using pointers.
This document discusses file operations in C including opening, reading, and writing to files. It covers:
- Using FILE * pointers to access files and opening files with fopen()
- Standard files stdin, stdout, stderr that are opened for input/output
- Reading/writing files using formatted I/O functions like fscanf() and fprintf() as well as lower level functions to get/put characters and lines
- Binary reading/writing entire blocks of memory with fread() and fwrite()
- Closing files, flushing buffers, and detecting the end of file
Pointers are variables that hold the memory address of another variable. A pointer variable contains the address of the variable it points to. Pointer variables must be declared with an asterisk and can be used to access and modify the value of the variable being pointed to using dereferencing operator. Pointers allow passing by reference in functions and dynamically allocating memory using functions like malloc and free. Pointer arithmetic allows treating pointers like arrays for accessing memory locations.
Literature Review Basics and Understanding Reference Management.pptxDr Ramhari Poudyal
Three-day training on academic research focuses on analytical tools at United Technical College, supported by the University Grant Commission, Nepal. 24-26 May 2024
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELgerogepatton
As digital technology becomes more deeply embedded in power systems, protecting the communication
networks of Smart Grids (SG) has emerged as a critical concern. Distributed Network Protocol 3 (DNP3)
represents a multi-tiered application layer protocol extensively utilized in Supervisory Control and Data
Acquisition (SCADA)-based smart grids to facilitate real-time data gathering and control functionalities.
Robust Intrusion Detection Systems (IDS) are necessary for early threat detection and mitigation because
of the interconnection of these networks, which makes them vulnerable to a variety of cyberattacks. To
solve this issue, this paper develops a hybrid Deep Learning (DL) model specifically designed for intrusion
detection in smart grids. The proposed approach is a combination of the Convolutional Neural Network
(CNN) and the Long-Short-Term Memory algorithms (LSTM). We employed a recent intrusion detection
dataset (DNP3), which focuses on unauthorized commands and Denial of Service (DoS) cyberattacks, to
train and test our model. The results of our experiments show that our CNN-LSTM method is much better
at finding smart grid intrusions than other deep learning algorithms used for classification. In addition,
our proposed approach improves accuracy, precision, recall, and F1 score, achieving a high detection
accuracy rate of 99.50%.
ACEP Magazine edition 4th launched on 05.06.2024Rahul
This document provides information about the third 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.
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesChristina Lin
Traditionally, dealing with real-time data pipelines has involved significant overhead, even for straightforward tasks like data transformation or masking. However, in this talk, we’ll venture into the dynamic realm of WebAssembly (WASM) and discover how it can revolutionize the creation of stateless streaming pipelines within a Kafka (Redpanda) broker. These pipelines are adept at managing low-latency, high-data-volume scenarios.
Using recycled concrete aggregates (RCA) for pavements is crucial to achieving sustainability. Implementing RCA for new pavement can minimize carbon footprint, conserve natural resources, reduce harmful emissions, and lower life cycle costs. Compared to natural aggregate (NA), RCA pavement has fewer comprehensive studies and sustainability assessments.
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...University of Maribor
Slides from talk presenting:
Aleš Zamuda: Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapter and Networking.
Presentation at IcETRAN 2024 session:
"Inter-Society Networking Panel GRSS/MTT-S/CIS
Panel Session: Promoting Connection and Cooperation"
IEEE Slovenia GRSS
IEEE Serbia and Montenegro MTT-S
IEEE Slovenia CIS
11TH INTERNATIONAL CONFERENCE ON ELECTRICAL, ELECTRONIC AND COMPUTING ENGINEERING
3-6 June 2024, Niš, Serbia
International Conference on NLP, Artificial Intelligence, Machine Learning an...gerogepatton
International Conference on NLP, Artificial Intelligence, Machine Learning and Applications (NLAIM 2024) offers a premier global platform for exchanging insights and findings in the theory, methodology, and applications of NLP, Artificial Intelligence, Machine Learning, and their applications. The conference seeks substantial contributions across all key domains of NLP, Artificial Intelligence, Machine Learning, and their practical applications, aiming to foster both theoretical advancements and real-world implementations. With a focus on facilitating collaboration between researchers and practitioners from academia and industry, the conference serves as a nexus for sharing the latest developments in the field.
2. Contents:
Introduction
Features
The list constructor ( ):
List slicing
Replace list items
Check if item exists in a list
Loop list
List comprehension
Built-in function
List methods
List operation
Unpacking list.
3. PYTHON DATA TYPES
Python supports 3 sequence data types:
1. LISTS
2. TUPLES
3. STRINGS
Other two important data structures in Python are:
1. SET
2. DICTIONARY
4. List is a collection which is ordered , mutable and indexed
Lists are created by square brackets and the elements in the list are separated
by commas.
Lists are used to store multiple items in a single entity.
Lists allow duplicates
LIST:
# exampleof lists
>>>games=['cricket','badminton','volleyball']
>>>print (games)
['cricket', 'badminton','volleyball']
>>>List=[1,2,,3,4,]
>>>print(List)
[1, 2, 3, 4]
5. List items are ordered means, items can be accessed using positional index. In general, new items
will be placed at the end of the list.
#Lists allow duplicate values:
>>>games=['cricket','badminton','volleyball','cricket','volleyball']
>>>print(games)
#output
['cricket','badminton', 'volleyball', 'cricket', 'volleyball']
>>> len(games)
5
Lists are mutablemeans we can change, add and remove items in a list after it has been created.
Since the list is indexed , lists can have items with same value.
Ordered:
Mutable:
Allows duplicate:
6. 1. List can contain elements of different data types i.e., string , int, Boolean, tuple etc. Lists are
Mutable
Features:
>>>list=['cricket','abc',42,29, 0, True]
>>>print(list)
#output
['cricket','abc', 42,29, 0, True]
>>>list=['cricket','abc',42,29.0,True]
>>>print(type(list))
#output
<class 'list'>
>>> list =[23, 45, 'krishna', (34,56)]
>>> print (list)
[23, 45, 'krishna', (34, 56)]
2. Lists are defined as objects with the data type ‘list’.
>>> list[1]='hello‘ ## mutability
>>> print (list) ## same memory reference
[23, 'hello', 'krishna', (34, 56)]
>>> list[3]=(89,'welcome')#mutability
>>> print (list)
[23, 'hello', 'krishna', (89, 'welcome')]
>>>len(list)
>>> list =[23, 45, 'krishna', (34,56)]
>>> print (list[2])# accessing list element
krishna
8. The list constructor ( ) :
It is also possible to use the
list ( ) constructor when
creating a new list.
x=list(('cricket','abc',42,29.0,True))
"""note
the double round-brackets"""
print(x)
#output:
['cricket','abc', 42,29.0, True]
Simple Operations on Lists
>> list1=[23, 55,77]
>>> list2=[23, 55, 77]
>>> list1==list2
True
>>> list1 is list2
False
>>> list2=list1
>>> list2 is list1
True
>>> d1=['a','b','c']
>>> d2=['a','b','d']
>>> d1<d2
True
>>> min(d1)
'a'
>>> max(d2)
'd‘
>>> sum(list1)
>>> list1=[20, 'hi', 40]
>>> list2=[20, 40, 'hi']
>>> list1==list2
False
>>> list1>list2
Traceback (most recent call last):
File "<pyshell#16>", line 1, in
<module>
list1>list2
TypeError: '>' not supported
between instances of 'str' and 'int'
>>> ["abc"]>["bac"]
False
>>> [45, 67, 89] + ['hi', 'hello']
[45, 67, 89, 'hi', 'hello']
9. Assignment and References
>>>x = 3
• First, an integer 3 is created and stored in memory
• A name x is created
• A reference to the memory location storing 3 is then
assigned to the name x
• So: When we say that the value of x is 3, we mean
that x now refers to the integer 3
Ex with immutable data like integers:
>>> x=10 # Creates 10, name x refers to 10
>>> y=x # Creates name y, refers to 10.
>>> id(x)
1400633408
>>> id(y) # x and y refer to same location
1400633408
>>> print(y)
10
>>> y=20 ## creates reference for 20
>>> id(y) ### changes y
1400633568 ## y points to a new mem location
>>> print (y)
20
>>> print(x) # no effect on x. Refers to 10
10
Note: Binding a variable in Python means
setting a name to hold a reference to some
object.
• Assignment creates references, not copies
x = y does not make a copy of the object y
references
x = y makes x reference the object y
references
10. List Assignment
>>> d=[1,2,3,4] ## d references the list [1,2,3,4]
>>> id (d)
56132040
>>> b=d ## b now references what d references
>>> id(b)
56132040
>>> b[3]=10 ## changes the list which b references
>>> print (b)
[1, 2, 3, 10]
>>> print (d) ### change reflected in original also
[1, 2, 3, 10]
>>>a=[23, 45, 'hi']
>>> b=a # two names refer to same memory
>>> id(a)
24931464
>>> id(b)
24931464 ## only one list. Two names refer to it
>>> a.append('welcome') ## change list element
>>> id(a)
24931464 # refer to same object
>>> print (a) [23, 45, 'hi', 'welcome']
>>> print (b)
## Change in one name affects the other
[23, 45, 'hi', 'welcome']
Lists are “mutable.”
When we change the values of list elements,
we do it in place.
We don’t copy them into a new memory
address each time.
If we type y=x and then modify y, both x
and y are changed
Note: b=a[:] creates copy of list a. Now we have
two independent copies and two references
12. Range of positive indexes:
We can specify a range of indexes by specifying where to start and where to end
the range.
# RETURN THE THIRD ,FOURTH AND FIFTH TERM:
>>>x=['cricket','badminton','volleyball','football','hockey','cheese']
print(x[2:5])
#output:
['volleyball', 'football', 'hockey']
2 3 4 Index number
NOTE: 1) The search will start at Index 2 ( included) and end at index 5 (not included).
2)Remember that the first item has index 0.
3)The index ranges from 0 to (n-1).
13. By leaving out the start value, by default the range will start
at the first item.
x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle']
print(x[:4])
#output:
[‘cricket’,’badminton’,’volleyball', 'football']
By leaving out the end value, by default the range will go
on to the end of the list.
x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle']
print(x[2:])
#output:
['volleyball', 'football', 'hockey', 'shuttle']
Herehockeyhasa
index value 4 and
isexcluded
becausetherange
isfrom0:(n-1)
0:(4-1)
i.e.,0:3
Herevolleyball hasa
index value 2 andis
included becausethe
range isfrom 2: last
itemin thelist
14. If you want to search the item from the end of the list , negative indexes can be
used.
>>>x=['cricket', 'badminton', 'volleyball',
'football','hockey', 'shuttle']
print(x[-3:-1])
#output:
['football', 'hockey']
-6 -5 -4
-3 -2 -1
Here the range is from
-3(included) : -1(excluded).
Shuttle is excluded because of
the range of index(-1).
Range of negative indexes:
15. To replace the value of a specific item ,refer to the index number.
Replace/Modify items in a List
#CHANGE THE SECOND ITEM IN A LIST:
x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle']
x[2]='PUBG‘
print(x)
#output:
['cricket', 'badminton', 'PUBG', 'football', 'hockey', 'shuttle']
Here volleyballis
replacedbyPUBG
• Replace a range of elements
To replace the value of items within a specific range, define a list with the new
values, and refer to the range of index numbers where you want to insert the new
values.
16. x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle']
x[4:]='PUBG','FREEFIRE’
print(x)
#Output:
['cricket', 'badminton', 'volleyball', 'football', 'PUBG', 'FREEFIRE']
We can also replace this line
by
x[4:6]=[‘PUBG,’FREEFIRE’]
If you insert more items than you replace , the new items will be inserted where you
specified, and the remaining itemsmove accordingly.
>>>x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle']
>>>len(x)
6
>>>x[2:3]='PUBG','FREEFIRE’
>>>print (x)
>>>len(x)
7
['cricket', 'badminton', 'PUBG', 'FREEFIRE', 'football', 'hockey', 'shuttle']
17. If you insert less items than you replace , the new items will be inserted where you specified,
and theremaining items move accordingly.
>>>x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle']
>>>x[2:4]=['PUBG']
print(x)
#Output:
['cricket', 'badminton', 'PUBG', 'hockey', 'shuttle']
Note: If the range of index which must be replaced is not equal to the item to be
replaced, the extra mentioned range of item is removed from the list … i.e., in the
range x[2:4] we can replace 2 items but we replaced only 1 item PUBG, hence
football is removedin the list.
Here square brackets are
must and necessary. If not
used the single item PUBG is
BY DEFAULT taken as 4
individual item as ‘P’,’U’
,’B’,’G’.
>>> list=[] #emptylist
>>> len (list)
0
>>> type(list)
>>> list=[34 ] # list with single element
>>> len (list)
1
>>> type(list)
<class 'list'>
18. x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle']
x[2:4]='PUBG'
print(x)
#Output:
['cricket', 'badminton', 'P','U', 'B', 'G', 'hockey', 'shuttle']
Here squarebrackets are
notusedhence the single
item PUBG is BY
DEFAULTtakenas 4
individualitemas‘P’,’U’
,’B’,’G’.
NOTE : The length of the list will change when the number of items
inserteddoes not match thenumber of itemsreplaced.
Check if item exists in a list:
To determine if a specified item is present in a list use the in keyword.
x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle']
if 'volleyball' in x:
print(“yes, ‘volleyball’ is in the list x”)
#output:
yes ‘volleyball’ is in the list x
19. List Comparison, use of is, in operator
>>> l1=[1,2,3,4]
>>> l2=[1,2,3,4]
>>> l3=[1,3,2,4]
>>> l1==l2
True
>>> l1==l3
False
>>> id(l1)
1788774040000
>>> id(l2)
1788777176704
>>> id(l3)
1788777181312
>>> l1 is l2
False
>>>> l1=['a','b','c','d']
>>> l2=['a','b','c','d']
>>> l1 is l2
False
>>> l1==l2
True
>>> if 'a' in l1:
print (" 'a' is present")
'a' is present
>>> if 'u' not in l1:
print (" 'u' is not present")
'u' is not present
20. Loop Through a List
You can loop through the list items by using
a for loop:
Loop list:
fruits=['apple','cherry','grapes']
for x in fruits:
print(x)
#Output:
apple
cherry
grapes
Loop Through the Index Numbers
• You can also loop through the list
items by referring to their index
number.
• Use the range() and len() functions
to create a suitable iterable.
fruits= ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(fruits[i])
#Output:
apple
banana
cherry
21. Using a While Loop:
• You can loop through the list items by using a while loop.
• Use the len() function to determine the length of the list, then start at 0 and
loop your way through the list items by referring to their indexes.
• Update the index by 1 after each iteration.
thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1
#Output:
apple
banana
cherry
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]
#Output:
apple
banana
cherry
Looping Using List Comprehension:
List Comprehension offers the shortest syntax
for looping through lists:
22. List Comprehension:
List comprehension offers a shorter syntax when you want to create a new list
based on the values of an existing list.
Example:
• Based on a list of fruits, you want a new list, containing only the fruits with the
letter "a" in the name.
['apple', 'banana', 'mango']
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [ ]
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
#Output:
• Without list comprehension you will have to write a for statement with a
conditional test inside:
This line specifies
that the newlist must
appendonlythe
fruits whichcontains
the letter‘a’ in them.
23. • With list comprehension one line of code is enough to create a new list:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruitsif "a" in x]
print(newlist)
#Output:
['apple', 'banana', 'mango']
• The Syntax:
newlist = [expression for item in iterable if condition == True]
• Condition:
The condition is like a filter that only accepts the items that evaluates to True.
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if x != "apple"]
print(newlist)
#Output:
['banana', 'cherry', 'kiwi', 'mango']
The
condition if x!= "apple" will
return True for all elements
other than "apple", making the
new list contain all fruits
except "apple".
Note: The iterable can be any iterable object, like a list, tuple, set etc.
Note: The expression is the
current item in the iteration, but
it is also the outcome, which you
can manipulate before it ends up
like a list item in the new list
24. Some examples of List Comprehension
>>> newlist = [x for x in range(10)]
>>> print (newlist)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
>>> newlist = [x for x in range(10) if x < 5]
>>> print (newlist)
[0, 1, 2, 3, 4]
>>> list1=['cricket','badminton', 'volleyball', 'football','hockey']
>>> newlist = [x.upper() for x in list1]
>>> print (newlist)
['CRICKET', 'BADMINTON', 'VOLLEYBALL', 'FOOTBALL', 'HOCKEY']
>>> newlist1 = ['welcome' for x in list1]
>>> print (newlist1)
['welcome', 'welcome', 'welcome', 'welcome', 'welcome']
25. Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list (creates a new list with same elements)
count() Returns the number of occurrences of the specified element
extend() Add the elements of a list (or any iterable), to the end of the current
list
index() Returns the index of the first occurrence of the specified element
insert() Adds an element at the specified position (without replacement)
pop() Removes the element at the specified position
remove() Removes the first occurrence of the specified element
reverse() Reverses the order of the list
sort() Sorts the list
Python has a set of built-in methods that you can use on lists.
List Methods:
26. To add an item to the end of the list, use the append() method:
x=['cricket', 'badminton', 'volleyball', 'football']
x.append('PUBG')
print(x)
#Output:
['cricket', 'badminton', 'volleyball', 'football', 'PUBG']
• To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index (without replacing)
Append items:
Insert items:
x=['cricket', 'badminton', 'volleyball', 'football']
x.insert(2,'PUBG')
print(x)
['cricket', 'badminton', 'PUBG', 'volleyball', 'football']
>>> d1=[23,45,67,3.14]
>>> d1.append(['hi',55])
>>> print (d1)
[23, 45, 67, 3.14, ['hi', 55]]
>>> len(d1)
5
27. • To append elements from another list to the current list, use
the extend() method. The items will be added at the end of the current list
sport=['cricket', 'badminton', 'volleyball', 'football']
fruits=['apple','cherry']
sport.extend(fruits)
print(sport)
['cricket', 'badminton', 'volleyball', 'football', 'apple', 'cherry']
#Output:
Extend list:
>>> list1=[1,2,3,4]
>>> list2=['a','b','c','d']
>>> list1.extend(list2)
>>> print(list1)
[1, 2, 3, 4, 'a', 'b', 'c', 'd']
>>> d1=[23,45,67,3.14]
>>>d1.extend( [‘hi’, 55])
>>> print(d1)
[23, 45, 67, 3.14, 'hi', 55]
>>> len(d1)
6
Note: 1) Extend operates on the
existing list taking another list as
argument. So, refers to same
memory
2) Append operates on the existing
list taking a singleton as argument
28. The extend() method can be used with any iterable object like tuples, sets,
dictionaries etc..
x=['cricket', 'badminton', 'volleyball', 'football'] # list
fruits=('apple','cherry') #tuple
x.extend(fruits)
print(x)
#Output:
['cricket', 'badminton', 'volleyball', 'football', 'apple', 'cherry']
• Remove Specified Item:
The remove() method removes the specified item.
Add any iterable:
Remove list items:
29. x=['cricket', 'badminton', 'volleyball', 'football']
x.remove('badminton')
print(x)
#Output:
['cricket', 'volleyball', 'football']
• Remove w.r.t Index:
The pop() method removes the specified index.
x=['cricket', 'badminton', 'volleyball', 'football']
x.pop(2)
print(x)
#Output:
['cricket', 'badminton', 'football']
Note: If you do not
specify the index,
the pop() method
removes the last item.
>>> list1=['cricket', 'badminton', 'volleyball', 'football', 'hockey']
>>> list1.pop()
'hockey'
>>> print(list1)
['cricket', 'badminton', 'volleyball', 'football']
Note: we can use
negative Indexing also
with pop() method
>>> list1=['cricket', 'badminton', 'volleyball', 'footba
>>> list1.pop(-2)
'hockey'
>>> print(list1)
['cricket', 'badminton', 'football']
30. • Deleting items:
• The del keyword also removes the specified index:
x=['cricket', 'badminton', 'volleyball', 'football']
del x[1]
print(x)
#Output:
['cricket', 'volleyball', 'football']
• The del keyword can also delete the list completely if index is not specified.
• The clear() method empties the list.
• The list still remains, but it has no content.
• Clear the List:
x=['cricket', 'badminton', 'volleyball', 'football']
x.clear()
print(x)
#Output:
[ ]
>>> list2=['a','b','c','d']
>>> del(list2[1])
>>> print (list2)
['a', 'c', 'd']
>>> list2=['a','b','c','d']
>>> del(list2)
>>> print (list2)
Traceback (most recent call last):
File "<pyshell#50>", line 1, in
<module>
print (list2)
NameError: name 'list2' is not
defined
31. Copy Lists:
There are many ways to make a copy, one way is
to use the built-in List method copy().
fruits = ["apple", "banana", "cherry"]
newlist = fruits.copy()
print(newlist)
#Output:
['apple', 'banana', 'cherry']
Another way to make a copy is to use
the built-in method list().
fruits = ["apple", "banana", "cherry"]
newlist = list(fruits)
print(newlist)
#Output:
['apple', 'banana', 'cherry']
A new list can be created with ‘+’ operator
similar to string concatenation.
>>> a=['hi', 'welcome']
>>> b=['to', 'python class']
>>> c=a+b # new list, new memory reference
>>> print ("new list after concatenation is:")
new list after concatenation is:
>>> print (c)
['hi', 'welcome', 'to', 'python class']
Creating new list using
existing lists (Concatenation)
Note: The * operator produces a new list that “repeats”
the original content
>>> print (a)
['hi', 'welcome']
>>> >>> print (a *3)
['hi', 'welcome', 'hi', 'welcome', 'hi', 'welcome']
32. Sort Lists:
• Sort list alphabetically:
List objects have a sort() method that will sort the list alphanumerically, ascending, by default:
['banana', 'kiwi', 'mango', 'orange', 'pineapple']
fruits = ["orange", "mango", "kiwi", "pineapple", "banana"]
fruits.sort()
print(fruits)
#Output:
num = [100, 50, 65, 82, 23]
num.sort()
print(num)
#Output:
• Sort the list numerically:
[23, 50, 65, 82, 100]
33. • Sort Descending:
• To sort descending, use the keyword argument reverse = True
fruits = ["orange", "mango", "kiwi", "pineapple", "banana"]
fruits.sort(reverse = True)
print(fruits)
#Output:
['pineapple', 'orange', 'mango', 'kiwi', 'banana']
• The reverse() method reverses the current sorting order of the elements.
>>> list1=[23, 'krishna', 'a', 56.44, 'hello']
>>> list1.sort()
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
list1.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
34. List operations:
Concatenation/joining lists
• There are several ways to
join, or concatenate, two or
more lists in Python.
• One of the easiest ways are
by using the + operator.
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
#Output:
['a', 'b', 'c', 1, 2, 3]
list1 = ["a", "b" , "c"]
list2 = [1, 2,3]
for x in list2:
list1.append(x)
print(list1)
#Output:
['a', 'b', 'c', 1, 2, 3]
Another way to
join two lists are
by appending all
the items from
list2 into list1, one
by one:
We can also use
the extend() method,
whose purpose is to
add elements from one
list to another list
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
#Output:
['a', 'b', 'c', 1, 2, 3]
35. ##list with append method
fruits = ["Apple", "Banana", "Mango"]
# using append() with user input
print(f'Current Fruits List {fruits}')
new = input("Please enter a fruit name:n")
fruits.append(new)
print(f'Updated Fruits List {fruits}')
Output:
Current Fruits List ['Apple', 'Banana', 'Mango']
Please enter a fruit name:
watermelon
Updated Fruits List ['Apple', 'Banana', 'Mango',
'watermelon']
## list with extend method
mylist = [ ] ### empty list
mylist.extend([1, "krishna"]) # extending list elements
print(mylist)
mylist.extend((34.88, True)) # extending tuple elements
print(mylist)
mylist.extend("hello") # extending string elements
print(mylist)
print ("number of elements in the list is:")
print (len(mylist))
Output:
[1, 'krishna']
[1, 'krishna', 34.88, True]
[1, 'krishna', 34.88, True, 'h', 'e', 'l', 'l', 'o']
numberof elements in the list is:
9
36. Unpacking lists:
Unpack list and assign them into multiple variables.
numbers=[1,2,3,4,5,6,7,8,9]
first,second,*others,last=numbers
print(first,second)
print(others)
print(last)
#Output:
1 2
[3, 4, 5, 6, 7, 8]
9
NOTE : The number of variables in the left side of the operator must be equal to the number of the list.. If
there are many items in the list we can use *others to pack the rest of the items into the list called other.
Packs the rest of the items.
Unpacks the first and second
item of the list.
Unpacks the last item of the
list.