Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1 views

Python Unit. 3

The document provides an overview of Python data structures including lists, tuples, dictionaries, and sets. It explains their characteristics, methods for creation, manipulation, and differences between these data types. Key features such as mutability, ordering, and methods for adding, updating, and removing elements are highlighted.

Uploaded by

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

Python Unit. 3

The document provides an overview of Python data structures including lists, tuples, dictionaries, and sets. It explains their characteristics, methods for creation, manipulation, and differences between these data types. Key features such as mutability, ordering, and methods for adding, updating, and removing elements are highlighted.

Uploaded by

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

Python Lists

In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can
store all types of items (including another list) in a list. A list may contain mixed type of items,
this is possible because a list mainly stores references at contiguous locations and actual items
maybe stored at different locations.
• List can contain duplicate items.
• List in Python are Mutable. Hence, we can modify, replace or delete the items.
• List are ordered. It maintain the order of elements based on how they are added.
• Accessing items in List can be done directly using their position (index), starting from 0
Creating a List
Here are some common methods to create a list:
Using Square Brackets
# List of integers
a = [1, 2, 3, 4, 5]

# List of strings
b = ['apple', 'banana', 'cherry']

# Mixed data types


c = [1, 'hello', 3.14, True]

print(a)
print(b)
print(c)

Creating List with Repeated Elements


We can create a list with repeated elements using the multiplication operator.
# Create a list [2, 2, 2, 2, 2]
a = [2] * 5

# Create a list [0, 0, 0, 0, 0, 0, 0]


b = [0] * 7

print(a)
print(b)

Adding Elements into List


We can add elements to a list using the following methods:
• append(): Adds an element at the end of the list.
• extend(): Adds multiple elements to the end of the list.
• insert(): Adds an element at a specific position.
# Initialize an empty list
a = []

# Adding 10 to end of list


a.append(10)
print("After append(10):", a)

# Inserting 5 at index 0
a.insert(0, 5)
print("After insert(0, 5):", a)

# Adding multiple elements [15, 20, 25] at the end


a.extend([15, 20, 25])
print("After extend([15, 20, 25]):", a)

Updating Elements into List


We can change the value of an element by accessing it using its index.
a = [10, 20, 30, 40, 50]

# Change the second element


a[1] = 25

print(a)
Removing Elements from List
We can remove elements from a list using:
• remove(): Removes the first occurrence of an element.
• pop(): Removes the element at a specific index or the last element if no index is
specified.
• del statement: Deletes an element at a specified index.
a = [10, 20, 30, 40, 50]

# Removes the first occurrence of 30


a.remove(30)
print("After remove(30):", a)

# Removes the element at index 1 (20)


popped_val = a.pop(1)
print("Popped element:", popped_val)
print("After pop(1):", a)

# Deletes the first element (10)


del a[0]
print("After del a[0]:", a)
List Methods
Let’s look at different list methods in Python:
• append(): Adds an element to the end of the list.
• copy(): Returns a shallow copy of the list.
• clear(): Removes all elements from the list.
• count(): Returns the number of times a specified element appears in the list.
• extend(): Adds elements from another list to the end of the current list.
• index(): Returns the index of the first occurrence of a specified element.
• insert(): Inserts an element at a specified position.
• pop(): Removes and returns the element at the specified position (or the last element if no
index is specified).
• remove(): Removes the first occurrence of a specified element.
• reverse(): Reverses the order of the elements in the list.
• sort(): Sorts the list in ascending order (by default).
Python List Slicing
Python list slicing is fundamental concept that let us easily access specific elements in a list. In
this article, we’ll learn the syntax and how to use both positive and negative indexing for slicing
with examples.
Example: Get the items from a list starting at position 1 and ending at position 4 (exclusive).
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Get elements from index 1 to 4 (excluded)
print(a[1:4])

Python List Slicing Syntax


list_name[start : end : step]
Parameters:
• start (optional): Index to begin the slice (inclusive). Defaults to 0 if omitted.
• end (optional): Index to end the slice (exclusive). Defaults to the length of list if omitted.
• step (optional): Step size, specifying the interval between elements. Defaults to 1 if
omitted
List Tuple Set Dictionary

A list is a non-
A Tuple is a non-
homogeneous data The set data A dictionary is also a
homogeneous data
structure that stores structure is non- non-homogeneous
structure that stores
the elements in homogeneous but data structure that
elements in columns of
columns of a single stores the elements stores key-value
a single row or
row or multiple in a single row. pairs.
multiple rows.
rows.

The dictionary can


The list can be A tuple can be The set can be
be represented by {
represented by [ ] represented by ( ) represented by { }
}

The Set will not The dictionary


The list allows Tuple allows duplicate
allow duplicate doesn’t allow
duplicate elements elements
elements duplicate keys.

The list can be A tuple can be nested The set can be The dictionary can
nested among all among all nested among all be nested among all

Example: {1: “a”, 2:


Example: [1, 2, 3, 4, Example: {1, 2, 3,
Example: (1, 2, 3, 4, 5) “b”, 3: “c”, 4: “d”, 5:
5] 4, 5}
“e”}

A list can be created Tuple can be created A set can be A dictionary can be
using using created using created using
the list() function the tuple() function. the set() function the dict() function.

A tuple is immutable
A list is mutable i.e A set is mutable i.e A dictionary is
i.e we can not make
we can make any we can make any mutable, its Keys are
any changes in the
changes in the list. changes in the set, not duplicated.
tuple.
List Tuple Set Dictionary

its elements are not


duplicated.

Dictionary is ordered
List is ordered Tuple is ordered Set is unordered (Python 3.7 and
above)

Creating an empty Creating an empty Creating a set Creating an empty


list Tuple dictionary
a=set()
l=[] t=() b=set(a) d={}
Tuples in Python
Python Tuple is a collection of objects separated by commas. A tuple is similar to a Python list
in terms of indexing, nested objects, and repetition but the main difference between both is
Python tuple is immutable, unlike the Python list which is mutable.
Here we use round brackets ()
t = (10, 20, 30)
print(t)
print(type(t))

What is Immutable in Tuples?


Unlike Python lists, tuples are immutable. Some Characteristics of Tuples in Python.
• Like Lists, tuples are ordered and we can access their elements using their index values
• We cannot update items to a tuple once it is created.
• Tuples cannot be appended or extended.
• We cannot remove items from a tuple once it is created.
t = (1, 2, 3, 4, 5)
# tuples are indexed
print(t[1])
print(t[4])

# tuples contain duplicate elements


t = (1, 2, 3, 4, 2, 3)
print(t)

# updating an element
t[1] = 100
print(t)
Accessing Values in Python Tuples
Tuples in Python provide two ways by which we can access the elements of a tuple.
Python Access Tuple using a Positive Index
Using square brackets we can get the values from tuples in Python
t = (10, 5, 20)
print("Value in t[0] = ", t[0])
print("Value in t[1] = ", t[1])
print("Value in t[2] = ", t[2])
Access Tuple using Negative Index
In the above methods, we use the positive index to access the value in Python, and here we will
use the negative index within [].
t = (10, 5, 20)
print("Value in t[-1] = ", t[-1])
print("Value in t[-2] = ", t[-2])
print("Value in t[-3] = ", t[-3])

Concatenation of Python Tuples


To Concatenation of Python Tuples, we will use plus operators(+).
t1 = (0, 1, 2, 3)
t2 = ('python', 'java')
# Concatenating above two
print(t1 + t2)

Nesting of Python Tuples


A nested tuple in Python means a tuple inside another tuple.
t1 = (0, 1, 2, 3)
t2 = ('python', 'java')

t3 = (t1, t2)
print(t3)

Output
((0, 1, 2, 3), ('python', 'java'))
Repetition Python Tuples
We can create a tuple of multiple same elements from a single element in that tuple.
t = ('python',)*3
print(t)

Slicing Tuples in Python


Slicing a Python tuple means dividing a tuple into small tuples using the indexing method. In
this example, we slice the tuple from index 1 to the last element. In the second print statement,
we printed the tuple using reverse indexing. And in the third print statement, we printed the
elements from index 2 to 4.
t = (0 ,1, 2, 3)
print(t[1:])
print(t[::-1])
print(t[2:4])
Output
(1, 2, 3)
(3, 2, 1, 0)
(2, 3)

Deleting a Tuple in Python


In this example, we are deleting a tuple using ‘del’ keyword. The output will be in the form of
error because after deleting the tuple, it will give a NameError.
Note: Remove individual tuple elements is not possible, but we can delete the whole Tuple
using Del keyword.
t = ( 0, 1)
del t
print(t)
Finding the Length of a Python Tuple
To find the length of a tuple, we can use Python’s len() function and pass the tuple as the
parameter.
t = ('python', 'java')
print(len(t))

Multiple Data Types With Tuple


Tuples in Python are heterogeneous in nature. This means tuples support elements with multiple
datatypes.
t = ("immutable", 12.5, 23)
print(t)

Converting a List to a Tuple


We can convert a list in Python to a tuple by using the tuple() constructor and passing the list as
its parameters.
a = [0, 1, 2]
t = tuple(a)
print(t)
Dictionaries in Python

A Python dictionary is a data structure that stores the value in key: value pairs. Values in a
dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and
must be immutable.
Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier to
find values.
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d)

How to Create a Dictionary


In Python, a dictionary can be created by placing a sequence of elements within curly {} braces,
separated by a ‘comma’.
d1 = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d1)
# create dictionary using dict() constructor
d2 = dict(a = "Geeks", b = "for", c = "Geeks")
print(d2)

• Dictionary keys are case sensitive: the same name but different cases of Key will be
treated distinctly.
• Keys must be immutable: This means keys can be strings, numbers, or tuples but not
lists.
• Keys must be unique: Duplicate keys are not allowed and any duplicate key will
overwrite the previous value.
• Dictionary internally uses Hashing. Hence, operations like search, insert, delete can be
performed in Constant Time.
Accessing Dictionary Items
We can access a value from a dictionary by using the key within square brackets orget()method.
d = { "name": "Alice", 1: "Python", (1, 2): [1,2,4] }

# Access using key


print(d["name"])

# Access using get()


print(d.get("name"))

Adding and Updating Dictionary Items


We can add new key-value pairs or update existing keys by using assignment.
d = {1: 'python', 2: 'java', 3: 'dotnet'}
# Adding a new key-value pair
d["age"] = 22
# Updating an existing value
d[1] = "php"
print(d)

Removing Dictionary Items


We can remove items from dictionary using the following methods:
• del: Removes an item by key.
• pop(): Removes an item by key and returns its value.
• clear(): Empties the dictionary.
• popitem(): Removes and returns the last key-value pair.
d = {1: 'python', 2: 'java', 3: 'php', 'age':22}
# Using del to remove an item
del d["age"]
print(d)
# Using pop() to remove an item and return the value
val = d.pop(1)
print(val)
# Using pop item to removes and returns
# the last key-value pair.
key, val = d.popitem()
print(f"Key: {key}, Value: {val}")
# Clear all items from the dictionary
d.clear()
print(d)

Iterating Through a Dictionary


We can iterate over keys [using keys() method] , values [using values() method] or both
[using item() method] with a for loop.
d = {1: 'Geeks', 2: 'For', 'age':22}
# Iterate over keys
for key in d:
print(key)
# Iterate over values
for value in d.values():
print(value)
# Iterate over key-value pairs
for key, value in d.items():
print(f"{key}: {value}")
Sets in Python

A Set in Python is used to store a collection of items with the following properties.
• No duplicate elements. If try to insert the same item again, it overwrites previous one.
• An unordered collection. When we access all items, they are accessed without any
specific order and we cannot access items using indexes as we do in lists.
• Internally use hashing that makes set efficient for search, insert and delete operations. It
gives a major advantage over a list for problems with these operations.
• Mutable, meaning we can add or remove elements after their creation, the individual
elements within the set cannot be changed directly.

Example of Python Sets


s = {10, 50, 20}
print(s)
print(type(s))

We can add and remove elements form the set with the help of the below functions –
• add(): Adds a given element to a set
• clear(): Removes all elements from the set
• discard(): Removes the element from the set
• pop(): Returns and removes a random element from the set
• remove(): Removes the element from the set

Table of Python Set Methods


Functions Name Description

add() Adds a given element to a set

clear() Removes all elements from the set


Functions Name Description

copy() Returns a shallow copy of the set

difference() Returns a set that is the difference between two sets

difference_update() Updates the existing caller set with the difference between two sets

discard() Removes the element from the set

frozenset() Return an immutable frozenset object

intersection() Returns a set that has the intersection of all sets

intersection_update() Updates the existing caller set with the intersection of sets

isdisjoint() Checks whether the sets are disjoint or not

issubset() Returns True if all elements of a set A are present in another set B

issuperset() Returns True if all elements of a set A occupies set B

pop() Returns and removes a random element from the set

remove() Removes the element from the set

Returns a set which is the symmetric difference between the two


symmetric_difference()
sets

symmetric_difference_update() Updates the existing caller set with the symmetric difference of sets
Functions Name Description

union() Returns a set that has the union of all sets

update() Adds elements to the set

You might also like