This document provides an introduction to Python data structures including lists, tuples, sets, and dictionaries. It describes how to define, access, and modify each type of data structure. It also covers file handling, string functions, exceptions, and other Python concepts. The key points are:
- Lists are the most versatile data type and can contain elements of different types. They can be accessed by index, sliced, modified via assignments to slices.
- Tuples are immutable sequences that are useful for grouping related data. They allow packing and unpacking of elements.
- Sets store unique elements and support mathematical operations like union and intersection.
- Dictionaries store mappings of unique keys to values. They allow
Other than some generic containers like list, Python in its definition can also handle containers with specified data types. Array can be handled in python by module named “array“. They can be useful when we have to manipulate only a specific data type values.
Arrays In Python | Python Array Operations | EdurekaEdureka!
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on 'Arrays in Python' will help you establish a strong hold on all the fundamentals in the Python programming language. Below are the topics covered in this PPT:
What is an array?
Is python list same as an array?
How to create arrays in python?
Accessing array elements
Basic array operations
- Finding the length of an array
- Adding Elements
- Removing elements
- Array concatenation
- Slicing
- Looping
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
METHODS DESCRIPTION
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
popitem() Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dict’s (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp() Compares elements of both dict.
Other than some generic containers like list, Python in its definition can also handle containers with specified data types. Array can be handled in python by module named “array“. They can be useful when we have to manipulate only a specific data type values.
Arrays In Python | Python Array Operations | EdurekaEdureka!
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on 'Arrays in Python' will help you establish a strong hold on all the fundamentals in the Python programming language. Below are the topics covered in this PPT:
What is an array?
Is python list same as an array?
How to create arrays in python?
Accessing array elements
Basic array operations
- Finding the length of an array
- Adding Elements
- Removing elements
- Array concatenation
- Slicing
- Looping
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
METHODS DESCRIPTION
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
popitem() Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dict’s (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp() Compares elements of both dict.
String literals in python are surrounded by either single quotation marks, or double quotation marks. Strings can be output to screen using the print function. For example: print("hello"). Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
This is presentation, that covers all the important topics related to strings in python. It covers storing, slicing, format, concatenation, modification, escape characters and string methods.
The file attatched also includes examples related to the slides shown.
A function is a set of statements that take inputs, do some specific computation and produces output. The idea is to put some commonly or repeatedly done task together and make a function, so that instead of writing the same code again and again for different inputs, we can call the function.
Python provides built-in functions like print(), etc. but we can also create your own functions. These functions are called user-defined functions.
2D array in C++ language ,define the concept of c++ Two-Dimensional array .with example .and also Accessing Array Components concept.and Processing Two-Dimensional Arrays.
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
String literals in python are surrounded by either single quotation marks, or double quotation marks. Strings can be output to screen using the print function. For example: print("hello"). Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
This is presentation, that covers all the important topics related to strings in python. It covers storing, slicing, format, concatenation, modification, escape characters and string methods.
The file attatched also includes examples related to the slides shown.
A function is a set of statements that take inputs, do some specific computation and produces output. The idea is to put some commonly or repeatedly done task together and make a function, so that instead of writing the same code again and again for different inputs, we can call the function.
Python provides built-in functions like print(), etc. but we can also create your own functions. These functions are called user-defined functions.
2D array in C++ language ,define the concept of c++ Two-Dimensional array .with example .and also Accessing Array Components concept.and Processing Two-Dimensional Arrays.
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 is the second slide I have shared for Python tutorial. I have prepared this slide to take session in my office to teach my co-workers. It helps to share knowledge and develop skill.
This presentation is a part of the COP2271C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce Freshmen students to both the process of software development and to the Python language.
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
A video of Dr. Anderson using these slides is available on YouTube at:
https://youtu.be/0ji1hOgcl44
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdffeelinggift
C++ project
Machine Problem 7 - Hashing
Write a program to do the following:
loads username/password sets from the file password.txt and insert them into the hash table until
the end of file is reached on password.txt. The password.txt file will look something like this
with one username/password set per line.
mary changeMe!
The program will then present a login prompt, read one username, present a password prompt,
and after looking up the username\'s password in the hash table, will print either \"Authentication
successful\" or \"Authentication failure\".
The above step will be repeated until the end of the input data (EOF) is reached on the console
input stream (cin). The EOF character on the PC\'s is the CTRL Z character.
To convert from a string to an integer, we can add the ascii value of each character together. For
instance, Mary\'s conversion from string to integer might look something like this:
109(\'m\') + 97(\'a\') + 114(\'r\') + 121(\'y\')=441
We\'ve converted the string to an integer, but we still need to convert the integer to an index. For
an array of 10 elements we can divide by 10 and use the remainder as an index. Combining these
two hash functions, we will get Mary\'s index to be: 441 % 10 = 1
Your primary tasks for this homework are to edit the login.cpp to replace the comments with
lines so that it does the following:
Insert passwords into the Hash Table.
Retrieve one user\'s Password structure from the Hash Table.
Compare retrieved user password to input password and print \"Authentication failure\" or
\"Authentication successful.\"
//--------------------------------------------------------------------
//
// listlnk.h
//
//--------------------------------------------------------------------
#pragma warning( disable : 4290 )
#include
#include
#include
#include
#include
#include
#include
using namespace std;
template < class T > // Forward declaration of the List class
class List;
template < class T >
class ListNode // Facilitator class for the List class
{
private:
ListNode(const T &nodeData, ListNode *nextPtr);
T dataItem; // List data item
ListNode *next; // Pointer to the next list node
friend class List;
};
//--------------------------------------------------------------------
template < class T >
class List
{
public:
List(int ignored = 0);
~List();
void insert(const T &newData) throw (bad_alloc); // Insert after cursor
void remove() throw (logic_error); // Remove data item
void replace(const T &newData) throw (logic_error); // Replace data item
void clear();
bool isEmpty() const;
bool isFull() const;
// List iteration operations
void gotoBeginning() throw (logic_error);
void gotoEnd() throw (logic_error);
bool gotoNext();
bool gotoPrior();
T getCursor() const throw (logic_error); // Return item
void showStructure() const;
void moveToBeginning() throw (logic_error); // Move to beginning
void insertBefore(const T &newElement) throw (bad_alloc); // Insert before cursor
private:
ListNode *head, // Pointer to the beginni.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
2. Introduction to lists
Python knows a number of compound data
types, used to group together other values. The
most versatile is the list, which can be written as
a list of comma-separated values (items)
between square brackets. List items need not
all have the same type.
3. >>> a = [100,200,300,400,500]
>>> a
[100,200,300,400,500]
Can be accessed with index values like arrays
in C/C++/Java.
>>> a[0]
100
Access the 2nd element from the end of the list
>>> a[-2]
400
4. Slicing: Extract values from the list within a
given index range.
nd
For eg. from the 2 element of the given list to
the last but one element.
>>> a[1:-1]
[200, 300, 400]
5. Some special cases
listobject[:x]
If x is a positive value, then x number of entries
–
from the beginning of the list would be sliced
>>a[:3]
[100, 200, 300]
If x is a negative value, for eg -2, then all the
–
entries from the list except the last 2 would be
sliced
>>> a[:-2]
[100, 200, 300]
6. Some special cases(contd...)
listobject[x:]
If x is positive, all the entries except for the first x
–
entries would be sliced
>>> a[2:]
[300, 400, 500]
If x is negative, for eg -2, then 2 entries from the
–
end of the list would be sliced
>>> a[-2:]
[400, 500]
7. Assignment to slices is also possible, and this
can even change the size of the list or clear it
entirely
>>> a[0:2] = [1, 12]
>>> a
[1, 12, 300, 400, 500]
Removing a slice
>>> a[0:2] = []
>>> a
[300, 400, 500]
8. Assignment to slices (special case)
You can empty the whole list with
>>> a[:] = []
>>> a
[]
10. Methods of the list data type
list.append(x)
●
Add an item to the end of the list
list.extend(L)
●
Extend the list by appending all the items in the
given list
11. list.insert(i, x)
●
Insert an item at a given position. The first argument
is the index of the element before which to insert, so
a.insert(0, x) inserts at the front of the list, and
a.insert(len(a), x) is equivalent to a.append(x)
list.remove(x)
●
Remove the first item from the list whose value is x.
It is an error if there is no such item.
list.index(x)
●
Return the index in the list of the first item whose
value is x. It is an error if there is no such item.
12. list.pop([i])
●
Remove the item at the given position in the list, and
return it. If no index is specified, a.pop() removes
and returns the last item in the list
list.count(x)
●
Return the number of times x appears in the list.
list.sort()
●
list.reverse()
●
13. Another way to remove entries from a list is
●
the use of the del statement
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]
14. Tuples
A tuple consists of a number of values
separated by commas, for instance:
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>>u = t, (1, 2, 3, 4, 5) # Tuples may
be nested
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4,
5))
15. Construct a single element tuple
●
>>> singleton = 'hello',
# note trailing comma
>>> singleton
('hello',)
The statement t = 12345,54321,'hello!'
is an example of tuple packing
16. Sequence unpacking
●
Sequence unpacking requires the list of
variables on the left to have the same number of
elements as the length of the sequence
>>> x, y, z = t
17. Sets
A set is an unordered collection with no
duplicate elements. Set objects also support
mathematical operations like union,
intersection, difference, and symmetric
difference.
18. >>> basket = ['apple', 'orange', 'apple',
'pear', 'orange', 'banana']
>>> fruit = set(basket)
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
# fast membership testing
>>> 'orange' in fruit
True
>>> 'crabgrass' in fruit
False
19. Set operations on unique letters from two words
>>> a = set('abracadabra')
>>> b = set('alacazam')
# unique letters in a
>>> a
set(['a', 'r', 'b', 'c', 'd'])
# letters in a but not in b
>>> a - b
set(['r', 'd', 'b'])
20. # letters in either a or b
>>> a | b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z',
'l'])
# letters in both a and b
>>> a & b
set(['a', 'c'])
# letters in a or b but not both
>>> a ^ b
set(['r', 'd', 'b', 'm', 'z', 'l'])
21. Dictionaries
Unordered set of key: value pairs, with the
requirement that the keys are unique (within
one dictionary)
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack':
4098}
22. The keys() method of the dictionary data type
returns a list of the keys.
>>> tel.keys()
['sape', 'jack', 'guido']
Both keys and values can either be strings or
numbers.
23. Build a dictionary from key-value pairs stored
●
as tuples
>>> dict([('sape', 4139), ('guido',
4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido':
4127}
Note the dict() constructor
24. Looping techniques
Use the iteritems() method to loop through
dictionaries
>>> knights = {’gallahad’: ’the pure’,
’robin’: ’the brave’}
>>> for k, v in knights.iteritems():
... print k, v
...
gallahad the pure
robin the brave
25. Looping over two sequences at the
same time
Use the zip() method
>>> a = ['foo','bar']
>>> b = [42, 0]
>>> for i,j in zip(a,b):
... print quot;%s:%dquot; % (i,j)
...
foo:42
bar:0
26. File objects
Quick introduction to file handling
●
open() returns a file object, and is most commonly
used with two arguments: ‘open(filename, mode)’
>>> f = open('temp.txt','w')
>>> f
<open file 'temp.txt', mode 'w' at
0xb7d4c5c0>
27. 'r'
●
The file must already exist, and it is opened in
read-only mode.
'w'
●
The file is opened in write-only mode. The file is
truncated and overwritten if it already exists, or
created if it does not exist.
28. 'a'
●
The file is opened in write-only mode. The file is
kept intact if it already exists, and the data you
write is appended to what's already in the file.
The file is created if it does not exist.
'r+'
●
The file must already exist and is opened for
both reading and writing, so all methods of f can
be called .
29. 'w+'
●
The file is opened for both reading and writing,
so all methods of f can be called. The file is
truncated and overwritten if it already exists, or
created if it does not exist.
'a+'
●
The file is opened for both reading and writing,
so all methods of f can be called. The file is kept
intact if it already exists, and the data you write
is appended to what's already in the file. The
file
is created if it does not exist.
30. Reading from a file object
●
f.read(size)
The size is an optional argument, which when
specified reads that many bytes at most. If
nothing is specified, it reads the contents of the
whole file and returns it as a string.
31. f.readline()
Reads a line from the file, returns it as a string
and moves on to the next line.
f.readlines()
This returns a list of all the lines in the file. Can
be used to loop through the contents of a file.
For eg
>>>for line in f.readlines():
... print line
...
32. Writing to a file
●
f.write(string)
It's simple!
Closing the file object
●
f.close()
Close the file and free up system resources
being used by the file object.
33. A few important string functions
s.split()
●
Splits a string consisting of words seperated by
whitespaces and returns a list of the words.
s.rstrip()
●
Remove whitespaces from the leading end or
the right side
s.lstrip()
●
35. Handling exceptions
Overall structure....
try:
#code that may cause runtime
#error
except [errortype]:
#handle the error
[else:]
#do something if no error raised
[finally:]
#irrespective of error being
#raised or not do something
36. >>> while True:
... try:
... x = int(raw_input(quot;enter a
number: quot;))
... break
... except ValueError:
... print quot;Oops!quot;
...
37. Raising exceptions
●
>>> raise NameError, ’HiThere’
Traceback (most recent call last):
File quot;<stdin>quot;, line 1, in ?
NameError: HiThere
Try this: Accept two numbers, raise a
ValueError when division by 0 is attempted and
handle it too