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

Python

The document provides a comprehensive overview of dictionaries and tuples in Python, including how to create, access, modify, and utilize built-in functions for both data structures. It explains key operations such as adding, removing, and updating key-value pairs in dictionaries, as well as indexing, slicing, and built-in functions for tuples. Additionally, it highlights the differences and similarities between tuples and lists.

Uploaded by

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

Python

The document provides a comprehensive overview of dictionaries and tuples in Python, including how to create, access, modify, and utilize built-in functions for both data structures. It explains key operations such as adding, removing, and updating key-value pairs in dictionaries, as well as indexing, slicing, and built-in functions for tuples. Additionally, it highlights the differences and similarities between tuples and lists.

Uploaded by

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

Dictionaries :

A dictionary is a collection of key-value pairs. dictionaries are defined with curly braces {}
Creating a Dictionary
We can create a dictionary by placing key-value pairs inside curly braces {}, separated by
colons :.
# Example of a simple dictionary
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
Accessing Values
can access values by referencing the key inside square brackets [] or using the get()
method.
# Accessing values
print(my_dict["name"]) # Output: Alice
print(my_dict.get("age")) # Output: 30
Modifying a Dictionary
You can add or modify key-value pairs.
# Modifying values
my_dict["age"] = 31 # Updates the age
my_dict["email"] = "alice@example.com" # Adds a new key-value pair
Built In Functions used on Dictionaries
Python provides several built-in functions and methods that can be used with dictionaries.
1. len()
Returns the number of key-value pairs in the dictionary.
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
print(len(my_dict)) # Output: 3
2. dict()
Creates a new dictionary. can create dictionaries in several ways using the dict() function.
# Creating an empty dictionary
new_dict = dict()
print(new_dict) # Output: {}
# Creating a dictionary from key-value pairs
new_dict = dict(name="Alice", age=30)
print(new_dict) # Output: {'name': 'Alice', 'age': 30}
# Creating a dictionary from a list of tuples
new_dict = dict([("name", "Alice"), ("age", 30)])
print(new_dict) # Output: {'name': 'Alice', 'age': 30}
3. keys()
Returns a view object that displays a list of all the keys in the dictionary.
my_dict = {"name": "Alice", "age": 30}
keys = my_dict.keys()
print(keys) # Output: dict_keys(['name', 'age'])
4. values()
Returns a view object that displays a list of all the values in the dictionary.
values = my_dict.values()
print(values) # Output: dict_values(['Alice', 30])
5. items()
Returns a view object that contains a list of the dictionary’s key-value pairs as tuples.
items = my_dict.items()
print(items) # Output: dict_items([('name', 'Alice'), ('age', 30)])
6. get()
Returns the value of a specified key. If the key does not exist, it returns None or a default
value.
# Existing key
print(my_dict.get("name")) # Output: Alice

# Non-existent key
print(my_dict.get("city", "Not found")) # Output: Not found
7. pop()
Removes a key-value pair from the dictionary and returns the value. If the key does not exist,
it raises a KeyError.
# Removing an existing key
age = my_dict.pop("age")
print(age) # Output: 30
print(my_dict) # Output: {'name': 'Alice'}
8. popitem()
Removes and returns the last inserted key-value pair as a tuple. If the dictionary is empty, it
raises a KeyError.
# Using popitem
last_item = my_dict.popitem()
print(last_item) # Output: ('name', 'Alice')
9. update()
Updates the dictionary with elements from another dictionary or an iterable of key-value
pairs.
python
my_dict = {"name": "Alice", "age": 30}

# Updating with another dictionary


my_dict.update({"age": 31, "city": "New York"})
print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York'}

# Updating with key-value pairs


my_dict.update([("email", "alice@example.com")])
print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York', 'email':
'alice@example.com'}
10. clear()
Empties the dictionary, removing all key-value pairs.
my_dict.clear()
print(my_dict) # Output: {}
11. copy()
Returns a shallow copy of the dictionary.
my_dict = {"name": "Alice", "age": 30}
new_dict = my_dict.copy()
print(new_dict) # Output: {'name': 'Alice', 'age': 30}
Dictionary Methods :
Python dictionaries come with a set of built-in methods that help in performing common
operations such as adding, removing, or manipulating key-value pairs.
Here are some useful methods for dictionaries:
 keys(): Returns a view object of all keys.
 values(): Returns a view object of all values.
 items(): Returns a view object of all key-value pairs (as tuples).
 clear(): Empties the dictionary.
 update(): Updates a dictionary with another dictionary or key-value pairs.
clear()

 Removes all the elements from the dictionary, leaving it empty.


my_dict = {"name": "Alice", "age": 30}
my_dict.clear()
print(my_dict) # Output: {}
2. copy()
Returns a shallow copy of the dictionary.
my_dict = {"name": "Alice", "age": 30}
new_dict = my_dict.copy()
print(new_dict) # Output: {'name': 'Alice', 'age': 30}

3. fromkeys()
Creates a new dictionary with keys from a sequence and sets all values to a specified value
(or None by default).
4. get()
Returns the value for the specified key. If the key doesn’t exist, it returns None or a specified
default value.
5. items()
Returns a view object of the dictionary's key-value pairs as tuples.
6. keys()
Returns a view object containing the dictionary's keys.
7. pop()
Removes the specified key and returns the associated value. If the key is not found, it raises
a KeyError. You can also provide a default value to avoid the error.
10. update()
Updates the dictionary with key-value pairs from another dictionary or an iterable of key-
value pairs. If a key already exists, its value is updated; if a key does not exist, it's added.
Method Description
clear() Removes all elements from the dictionary.
copy() Returns a shallow copy of the dictionary.
fromkeys() Creates a new dictionary with keys from a sequence and a specified value.
get() Returns the value for the specified key, or a default value.
items() Returns a view object of the dictionary’s key-value pairs.
keys() Returns a view object of the dictionary’s keys.
pop() Removes and returns the value for the specified key.
popitem() Removes and returns the last inserted key-value pair.
setdefault() Returns the value of a key, or sets it to a default if missing.
update() Updates the dictionary with key-value pairs from another dictionary or iterable.
values() Returns a view object of the dictionary’s values.
Del statement
The del statement in Python is used to delete objects. It can be used to remove elements
from lists or dictionaries, delete variables, or even delete slices from a list.
Syntax:
del object
Use Cases of del in Python
1. Deleting a Dictionary Key-Value Pair: You can use del to remove a specific key-value
pair from a dictionary.
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
del my_dict["age"] # Deletes the key 'age'
print(my_dict) # Output: {'name': 'Alice', 'city': 'New York'}
Deleting Variables: The del statement can delete a variable, which means that the variable
will no longer exist.
x = 10
del x
# print(x) # This will raise a NameError because x is deleted
Deleting Elements from a List: You can remove an element at a specific index in a list using
del.
my_list = [1, 2, 3, 4, 5]
del my_list[2] # Deletes the element at index 2
print(my_list) # Output: [1, 2, 4, 5]
Deleting a Slice from a List: You can delete multiple elements by specifying a slice.
my_list = [1, 2, 3, 4, 5]
del my_list[1:3] # Deletes elements from index 1 to 2 (slicing)
print(my_list) # Output: [1, 4, 5]
Deleting Objects: You can use del to delete an entire object, such as a list, dictionary, or class
instance.
my_list = [1, 2, 3]
del my_list
# print(my_list) # Raises NameError as my_list no longer exists
Tuples and Sets :
Tuples in Python
A tuple is an immutable, ordered sequence of elements. Unlike lists, the elements in a tuple
cannot be modified (added, removed, or changed) after it is created. Tuples are commonly
used to store collections of items that should not change.
Creating Tuples
You can create a tuple by enclosing elements in parentheses () separated by commas.
Ways to Create Tuples in Python
1. Creating a Tuple with Multiple Elements: You can create a tuple by placing elements
inside parentheses and separating them with commas.
# Tuple with integers
my_tuple = (1, 2, 3, 4)
print(my_tuple) # Output: (1, 2, 3, 4)

# Tuple with mixed data types


mixed_tuple = (1, "Hello", 3.14, True)
print(mixed_tuple) # Output: (1, 'Hello', 3.14, True)
Creating a Tuple Without Parentheses: Parentheses are optional when creating tuples with
multiple elements (known as tuple packing).
my_tuple = 1, 2, 3
print(my_tuple) # Output: (1, 2, 3)
Creating a Tuple with a Single Element: When creating a tuple with only one element, you
must include a trailing comma after the element. This is required to distinguish a tuple from
a simple expression.
single_element_tuple = (5,)
print(type(single_element_tuple)) # Output: <class 'tuple'>

# Without the trailing comma, it will not be a tuple


not_a_tuple = (5)
print(type(not_a_tuple)) # Output: <class 'int'>
Empty Tuple: You can create an empty tuple by simply using empty parentheses.
empty_tuple = ()
print(empty_tuple) # Output: ()
Basic Tuple Operations
Accessing Tuple Elements
You can access tuple elements using indexing (starting from 0).
my_tuple = (10, 20, 30)
print(my_tuple[0]) # Output: 10
print(my_tuple[-1]) # Output: 30 (last element)
Slicing Tuples
You can slice tuples to get a range of elements.
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4]) # Output: (2, 3, 4)
Concatenating Tuples
You can concatenate two or more tuples using the + operator.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
result = tuple1 + tuple2
print(result) # Output: (1, 2, 3, 4, 5, 6)
Repeating Tuples
You can repeat the elements of a tuple using the * operator.
my_tuple = (1, 2)
result = my_tuple * 3
print(result) # Output: (1, 2, 1, 2, 1, 2)
Finding Length of a Tuple
Use the len() function to find the number of elements in a tuple.
my_tuple = (10, 20, 30)
print(len(my_tuple)) # Output: 3
tuple() Function
The tuple() function in Python is a built-in constructor that is used to create a tuple from an
iterable. This can be a list, string, range, or any other object that can return its elements one
at a time.
Syntax:
tuple([iterable])
iterable (optional): Any iterable (like list, string, or range). If no iterable is passed, an empty
tuple is created.
Examples of Using tuple()
1. Converting a List to a Tuple: You can use the tuple() function to convert a list into a
tuple.
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3)
Converting a String to a Tuple: Each character of the string is treated as an element of the
tuple.
my_string = "hello"
my_tuple = tuple(my_string)
print(my_tuple) # Output: ('h', 'e', 'l', 'l', 'o')
Creating an Empty Tuple: If you call the tuple() function without passing an iterable, it
returns an empty tuple.
empty_tuple = tuple()
print(empty_tuple) # Output: ()
Indexing and Slicing in tuples :
In Python, tuples support indexing and slicing, which allows you to access elements or
subsets of elements from the tuple. Since tuples are ordered collections, you can use indices
to refer to the elements.
Indexing in Tuples
Indexing allows you to access individual elements of a tuple using their position (index).
Indexing in Python starts at 0 for the first element.
Syntax:
tuple_name[index]
Examples of Indexing:
1. Accessing elements using positive indices:
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[0]) # Output: 10 (first element)
print(my_tuple[2]) # Output: 30 (third element)
Accessing elements using negative indices: Negative indices start from -1, which refers to
the last element of the tuple, -2 refers to the second-to-last element, and so on.
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[-1]) # Output: 50 (last element)
print(my_tuple[-3]) # Output: 30 (third-to-last element)
Slicing in Tuples
Slicing allows you to retrieve a subset of elements from a tuple. It uses a colon (:) to specify
the start, stop, and optional step values.
Syntax:
tuple_name[start:stop:step]
 start: The index to start the slice (inclusive).
 stop: The index to end the slice (exclusive).
 step: The step or interval between elements (optional; default is 1).
Examples of Slicing:
1. Basic Slicing: Extract a range of elements by specifying the start and stop values.
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[1:4]) # Output: (20, 30, 40) (from index 1 to 3)
Negative Indexing in Slicing: You can use negative indices to slice from the end of the tuple.
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[-4:-1]) # Output: (20, 30, 40) (from index -4 to -2)
Examples of Indexing and Slicing:
# Tuple for demonstration
my_tuple = (10, 20, 30, 40, 50, 60)

# Indexing
print(my_tuple[0]) # Output: 10
print(my_tuple[-1]) # Output: 60

# Slicing
print(my_tuple[1:4]) # Output: (20, 30, 40)
print(my_tuple[:3]) # Output: (10, 20, 30)
print(my_tuple[2:]) # Output: (30, 40, 50, 60)
print(my_tuple[::2]) # Output: (10, 30, 50)
print(my_tuple[::-1]) # Output: (60, 50, 40, 30, 20, 10) # Reversing tuple
Built in functions used on Tuples :
Python provides several built-in functions that can be used to perform operations on tuples.
Here are some commonly used built-in functions for tuples:
1. len()
The len() function returns the number of elements in the tuple.
my_tuple = (10, 20, 30, 40)
print(len(my_tuple)) # Output: 4
2. max()
The max() function returns the largest element in the tuple. All elements in the tuple must
be comparable.
my_tuple = (10, 20, 30, 40)
print(max(my_tuple)) # Output: 40
3. min()
The min() function returns the smallest element in the tuple.
my_tuple = (10, 20, 30, 40)
print(min(my_tuple)) # Output: 10
4. sum()
The sum() function returns the sum of all elements in the tuple. All elements must be
numeric.
my_tuple = (10, 20, 30)
print(sum(my_tuple)) # Output: 60
Relation Between Tuples and Lists
Tuples and lists in Python are both sequences used to store collections of items, but they
have key differences and similarities.
Similarities Between Tuples and Lists:
1. Ordered: Both tuples and lists are ordered collections. This means that elements
have a defined sequence and can be accessed using their index (starting from 0).
o
my_list = [10, 20, 30]
my_tuple = (10, 20, 30)
print(my_list[1]) # Output: 20
print(my_tuple[1]) # Output: 20
Indexing and Slicing: Both lists and tuples support indexing and slicing operations to access
elements or subsets of elements.
my_list = [1, 2, 3, 4, 5]
my_tuple = (1, 2, 3, 4, 5)
print(my_list[2:4]) # Output: [3, 4]
print(my_tuple[2:4]) # Output: (3, 4)
Differences Between Tuples and Lists:
Feature Lists Tuples
Lists are mutable (you can
Tuples are immutable (you cannot change
Mutability change, add, or remove
or modify elements once defined).
elements).
Syntax Defined using square brackets []. Defined using parentheses ().
Slightly slower due to mutability Faster than lists because of immutability
Performance
and additional memory usage. (less memory overhead).
Ideal when you need to modify
Ideal for read-only or constant data where
Use Cases the collection (adding, removing,
no modifications are needed.
or updating elements).
Memory Lists consume more memory due Tuples consume less memory because
Usage to the ability to grow and shrink. they are fixed in size.
Lists have more built-in methods
Methods Tuples have fewer methods (only count()
like append(), remove(), and
Available and index() are available).
pop().
Lists are not hashable, so they Tuples are hashable (if they contain only
Hashability cannot be used as dictionary immutable elements), so they can be used
keys or elements in sets. as dictionary keys and in sets.

Relation between Tuples and Dictionaries


  Tuples and dictionaries are built-in Python data structures that can store multiple
items in a single variable.
 Differences Between Tuples and Dictionaries:
Feature Tuple Dictionary
An unordered collection of key-value
Definition An ordered collection of elements.
pairs.
Defined using curly braces {} with key-
Syntax Defined using parentheses ().
value pairs.
Dictionaries are mutable (you can add,
Mutability Tuples are immutable.
remove, or modify key-value pairs).
Element Accessed by index. Accessed by key.
Feature Tuple Dictionary
Access
Tuple elements do not need to be
Uniqueness Dictionary keys must be unique.
unique.
Ordered (insertion order is Ordered (insertion order is preserved
Order
preserved). since Python 3.7+).
Store sequences of items where Store data with meaningful labels (keys)
Use Cases
order matters but doesn't change. associated with each value.
Tuples can be hashable (if all Dictionaries are not hashable because
Hashability
elements are hashable). they are mutable.

Using zip() Function


The zip() function in Python is used to combine multiple iterables (e.g., lists, tuples, or strings) into
an iterator of tuples, where each tuple contains one element from each of the input iterables. It's
commonly used for iterating over two or more sequences in parallel.
Syntax:
zip(iterable1, iterable2, ...)
The zip() function returns an iterator of tuples, where each tuple contains elements from the
corresponding position of the provided iterables.
Basic Example:
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

# Zipping two lists together


zipped = zip(list1, list2)

# Converting the iterator to a list


print(list(zipped)) # Output: [(1, 'a'), (2, 'b'), (3, 'c')]
Sets in Python
A set is an unordered, mutable collection of unique elements. Since sets are unordered, they do not
support indexing, slicing, or any other sequence-like behavior. Sets are commonly used to remove
duplicate elements from a collection or to perform mathematical set operations like union,
intersection, etc.
Creating Sets
You can create a set by enclosing elements in curly braces {} or using the set() constructor.
# Creating a set
my_set = {1, 2, 3, 4}
print(my_set) # Output: {1, 2, 3, 4}

# Creating an empty set (using set())


empty_set = set()
print(empty_set) # Output: set()

# Duplicate elements are automatically removed


my_set = {1, 2, 2, 3}
print(my_set) # Output: {1, 2, 3}
Set Operations
1. Adding Elements to a Set: You can add elements to a set using add().
Removing Elements from a Set: You can remove elements using remove() or discard(). The
difference is that remove() raises an error if the element is not found, while discard() does
not.
Set Union (|): Returns a new set containing all elements from both sets (i.e., combines both
sets).
Set Methods:
 add(element): Adds an element to the set.
 discard(element): Removes an element if it is present. Does not raise an error if the
element is not found.
 remove(element): Removes an element. Raises a KeyError if the element is not
found.
 pop(): Removes and returns an arbitrary element from the set. Raises a KeyError if
the set is empty.
 clear(): Removes all elements from the set.
 copy(): Returns a shallow copy of the set.
 union(other_set): Returns a new set with elements from the set and other_set.
 intersection(other_set): Returns a new set with elements common to the set and
other_set.
 difference(other_set): Returns a new set with elements in the set that are not in
other_set.
 symmetric_difference(other_set): Returns a new set with elements in either set but
not both.
Frozenset
In Python, a frozenset is an immutable version of a set. Unlike regular sets, frozensets cannot
be modified after they are created. This immutability makes frozensets hashable and thus
usable as dictionary keys or elements of other sets.
Creating a frozenset:
1. Using the frozenset() Constructor:
# Creating a frozenset from a list
my_frozenset = frozenset([1, 2, 3, 4])
print(my_frozenset) # Output: frozenset({1, 2, 3, 4})
From a Set:
my_set = {1, 2, 3, 4}
my_frozenset = frozenset(my_set)
print(my_frozenset) # Output: frozenset({1, 2, 3, 4})
Creating an Empty frozenset:
empty_frozenset = frozenset()
print(empty_frozenset) # Output: frozenset()

You might also like