0% found this document useful (0 votes)
10 views

BData Structure

Lists and tuples are data structures that allow storing multiple elements in Python. Lists are ordered, changeable sequences while tuples are ordered and unchangeable. Some key differences are: - Lists use square brackets while tuples use parentheses - List items are mutable and can be changed, added or removed while tuple items are immutable - Lists allow duplicates but tuples do not - Common list methods include append(), pop(), insert() while common tuple operations include accessing items and determining length.

Uploaded by

arjun
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

BData Structure

Lists and tuples are data structures that allow storing multiple elements in Python. Lists are ordered, changeable sequences while tuples are ordered and unchangeable. Some key differences are: - Lists use square brackets while tuples use parentheses - List items are mutable and can be changed, added or removed while tuple items are immutable - Lists allow duplicates but tuples do not - Common list methods include append(), pop(), insert() while common tuple operations include accessing items and determining length.

Uploaded by

arjun
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Module – 2

Data Structures
Prepared by:
Shweta Dhareshwar
Department of MCA
Lists

• Lists are used to store multiple items in a single variable.


• List is a collection which is ordered and changeable.
• Allows duplicate members.
• In Python lists are written with square brackets.
Example :
mylist = [“red", "blue", “pink"]
print(mylist)
List Items

• List items are ordered, changeable, and allow duplicate values.


• List items are indexed, the first item has index [0], the second item has index [1] etc.
• Ordered : When we say that lists are ordered, it means that the items have a defined
order, and that order will not change.
• Changeable : The list is changeable, meaning that we can change, add, and remove
items in a list after it has been created.
• Allow Duplicates : Since lists are indexed, lists can have items with the same value.
List Items

List items can be of any data type:


Example : String, int and boolean data types:
type()
Example : A list with strings, integers and •From Python's perspective, lists are defined as
boolean values:
objects with the data type 'list':
<class 'list'>
Example : What is the data type of a list?
Basic List Operations
Access Items :
•List items are indexed and you can access them by referring to the
index number:
Example : Print the second item of the list:

Note: The first item has index 0.


Continued………..

• Updating List – We can update the existing item of the list with the help
of the index.
• Deleting list Item- With the help of del and list index, we can delete any
item by specifying its index.
• Addition of the List – Two lists can be added using the + operator.
• Multiplication of List -
Built-In Functions Used on Lists
• len()-Python list method len() returns the number of elements in the list.
• Max() - max returns the elements from the list with maximum value.
• Min() - min() returns the elements from the list with minimum value.
List Methods
Python List provides different methods to add items to a list.
append() - The append() method adds an item at the end of the list.
For example:
numbers = [21, 34, 54, 12]
print("Before Append:", numbers)
# using append method
numbers.append(32)
print("After Append:", numbers)
• extend()- We use the extend() method to add all items of one list to another.
List.extend(sequence)
For example:
prime_numbers = [2, 3, 5]
print("List1:", prime_numbers)
even_numbers = [4, 6, 8]
print("List2:", even_numbers)
# join two lists
prime_numbers.extend(even_numbers)
print("List after extend:", prime_numbers)
• Clear() - removes all items from the list.
Example :
prime_numbers = [2, 3, 5]
prime_numbers.clear()
• Copy() - returns the shallow copy of the list.
• list.copy()
prime_numbers = [2, 3, 5]
prime_numbers1=prime_numbers.copy()
• count()- returns the count of the specified item in the list.
• list.count(item)
prime_numbers = [2, 3, 5]
prime_numbers.count (2)
• index()- returns the index of the first matched item
list.index(item)
prime_numbers = [2, 3, 5]
X= prime_numbers.index(2)
• insert() -inserts an item at the specified index
prime_numbers = [2, 3, 5]
prime_numbers.insert (2,8)
• pop() - returns and removes item present at the given index
prime_numbers = [2, 3, 5]
prime_numbers.pop(2)
• reverse()- reverses the item of the list.
prime_numbers.reverse()
print(prime_numbers)
• sort() - sort the list in ascending/descending order.
prime_numbers.sort()
print(prime_numbers)
• Join () - There are several ways to join, or concatenate, two or more lists in Python.
Example:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
List Methods
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
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Negative Indexing

•Negative indexing means start from the end


•-1 refers to the last item, -2 refers to the second last item etc.
Example : Print the last item of the list:
Range of Indexes
•You can specify a range of indexes by specifying where to start and where to end
the range.
•When specifying a range, the return value will be a new list with the specified
items.
Example : Return the third, fourth, and fifth item:
Range of Negative Indexes

Specify negative indexes if you want to start the search from the end of the list:
Example :
This example returns the items from "orange" (-4) to, but NOT including
"mango" (-1):
Strings

• Strings in Python are arrays of bytes representing unicode


characters.
• Python does not have a character data type a single
character is simply a string with a length of 1.
Creating String
• Strings in python are surrounded by either single quotation marks, or double quotation marks with
‘=‘.
• You can display a string literal with the print() function or Assign String to a Variable.
Multiline Strings:-
You can assign a multiline string to a variable by using three quotes.
Eg: x=“””Good morning all,
I am from MCA section A,
I study Python”””
print(x)
Looping through a string
Eg: for i in “MCA”
print(i)
Accessing Characters in String

• Square brackets can be used to access elements of the string.


Ex: a = "Hello, World!"
print(a[1])
Basic String Operations

String Length:To get the length of a string, use the len() function.
Ex: str=“Good Morning”
print(len(str))
Check String : To check if a certain phrase or character is
present in a string, we can use the keyword in.
Ex: txt = "The best things in life are free!"
print("free" in txt)
Check if NOT: To check if a certain phrase or character is
NOT present in a string, we can use the keyword not in.
Ex: txt = "The best things in life are free!"
print(“sky" not in txt)
String Slicing

• You can return a range of characters by using the slice syntax.


• Specify the start index and the end index, separated by a colon, to return a
part of the string.
Given string [start : End : Step]
b = "Hello, World!"
print(b[2:5])
print(b[2:7:2])
print(b[2:12:3])
String Methods
count ()
Syntax:
str.count(substr,start,end)
find()
Syntax:
str.find(given_str,beg=0 end=len(string))
Justify- ljust()
Str.ljust(given_length,fillchar)
Rjust()
Str.rjustWidth[,fillchar]
• lower(): Converts all uppercase characters in a string into lowercase
• upper(): Converts all lowercase characters in a string into uppercase
• title(): Convert string to title case
• swapcase(): Swap the cases of all characters in a string
• capitalize(): Convert the first character of a string to uppercase
• replace() :Replaces all occurrences of a substring with another substring
• strip() : Returns the string with both leading and trailing characters
• Split() : The split() method splits a string into a list.
text = “Good morNing eVeryone”
print("\nConverted String:")
print(text.upper())
# lower() function to convert
# convert the first character of a string to uppercase
# string to lower case
print("\nConverted String:")
print("\nConverted String:")
print(text.replace(“good”,”to”))
print(text.lower())
print(text)
# converts the first character to
Print(text.lstrip())
# upper case and rest to lower case
x = text.split()
print("\nConverted String:")
print(x)
print(text.title())
#swaps the case of all characters in the string
# upper case character to lowercase and viceversa
print("\nConverted String:")
print(text.swapcase())
# convert the first character of a string to uppercase
print("\nConverted String:")
print(text.capitalize())
# original string never changes
print("\nOriginal String")
print(text)
TUPLES

mytuple = ("apple", "banana", "cherry")


•Tuples are used to store multiple items in a single variable.
•Tuple is a collection which is ordered and unchangeable.
•Allows duplicate members.
•In Python tuples are written with round brackets.
•Tuple items are ordered, unchangeable, and allow duplicate values.
•Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
• To create a tuple with only one item, you have to add a comma after
the item, otherwise Python will not recognize it as a tuple.
Example : One item tuple, remember the comma:
Tuple Length

• To determine how many items a tuple has, use the len() method
Format strings
• It is also known as string interpolation or string formatting, are a way to dynamically insert values into a string in
Python. They allow you to create formatted output by specifying placeholders within a string and providing the
values to replace those placeholders.
• In Python, there are several ways to format strings, but one commonly used method is using the .format() method.
Here's an example:
name = “Amar"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
In this example, the string "My name is {} and I am {} years old." contains two placeholders {}. The .format() method is
called on the string and the values to be inserted are provided as arguments within the parentheses. The values "Amar"
and 25 are passed in the same order as the placeholders, and they replace the placeholders in the resulting output.
• You can also specify the order of the values explicitly by using numbers
within the curly braces. For example:
name = "Amar"
age = 25
print("My name is {0} and I am {1} years old. {0}!".format(name, age))
In this case, {0} refers to the first value (name), and {1} refers to the second
value (age). By repeating {0}, we can use the same value multiple times within
the string.
Dictionary
• Dictionary it is a data structure , which contains key and value pairs. It is
written as a sequence of the key/value or item separated by commas.
• Eg: dict1 = { "brand": "Ford", "model": "Mustang", "year": 1964}

• Creating a Dictionary – A dictionary can be created by placing a


sequence of elements within curly {} braces, separated by ‘comma’.
• An empty Dictionary can be created by just two curly braces {}.
Accessing values of a Dictionary
• In order to access the items of a dictionary refer to its key name. Key can
be used inside square brackets.
dict1 = { "brand": "Ford", "model": "Mustang", "year": 1964}
print(dict1[‘brand’])
print(dict1[‘color’])
Deleting item from Dictionary
• The items of the dictionary can be deleted by using the del keyword.
del dict1[key]
• You can delete a single item as well as entire dictionary.
dict2 = {1:"Python", 2: "Java", 3: "Ruby", 4:"Scala"}
del(dict2[1])
print("Data after deletion Dictionary=")
print(dict2)
print(dict2[1])
Updating and Adding in the Dictionary
• dict[key] = new_value
• To update we need to specify the values’ key in the square bracket and assign a new value. If
the key is not present, then the key-value pair would be added.
Eg: Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict[0] = “MA”
Dict[2] = “DBMS”
Dict[3] = 1
print("\n Dictionary after adding 3 elements: ")
print(Dict)
Dict[3] = “Java”
print(Dict)
Dictionary Functions

You might also like