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

Python Container Operations

The document provides examples of common list, dictionary, and set methods in Python. It demonstrates how to append, insert, remove, sort, and iterate over elements in lists. For dictionaries, it shows how to add, access, modify, and iterate over key-value pairs. And for sets, it shows how to add/remove elements and perform set operations like union, intersection, difference and symmetric difference.

Uploaded by

umang.497.ua
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Python Container Operations

The document provides examples of common list, dictionary, and set methods in Python. It demonstrates how to append, insert, remove, sort, and iterate over elements in lists. For dictionaries, it shows how to add, access, modify, and iterate over key-value pairs. And for sets, it shows how to add/remove elements and perform set operations like union, intersection, difference and symmetric difference.

Uploaded by

umang.497.ua
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

List

# Sample list
my_list = [3, 1, 5, 2, 4]

# append(item): Adds an element to the end of the list


my_list.append(6) # [3, 1, 5, 2, 4, 6]

# extend(iterable): Extends the list by appending elements from the iterable


my_list.extend([7, 8]) # [3, 1, 5, 2, 4, 6, 7, 8]

# insert(index, item): Inserts an element at a specific position in the list


my_list.insert(2, 9) # [3, 1, 9, 5, 2, 4, 6, 7, 8]

# remove(item): Removes the first occurrence of a specific element from the list
my_list.remove(5) # [3, 1, 9, 2, 4, 6, 7, 8]

# pop(index=-1): Removes and returns the element at the specified index, or the last
element if no index is provided
popped_element = my_list.pop(3) # [3, 1, 9, 4, 6, 7, 8], popped_element = 2

# index(item, start=0, end=len(list)): Returns the index of the first occurrence of a


specified element within a given range of the list
index = my_list.index(6) # 4

# count(item): Returns the number of occurrences of a specified element in the list


count = my_list.count(9) # 1

# sort(key=None, reverse=False): Sorts the list in place, optionally using a custom key
function and specifying the sort order
my_list.sort() # [1, 3, 4, 6, 7, 8, 9]

# reverse(): Reverses the order of the elements in the list


my_list.reverse() # [9, 8, 7, 6, 4, 3, 1]

# clear(): Removes all elements from the list


my_list.clear() # []

# copy(): Returns a shallow copy of the list


copied_list = my_list.copy() # []

# len(list): Returns the number of elements in the list


length = len(my_list) # 0

# max(iterable, default=None): Returns the maximum element in the list or an iterable, or a


default value if the list is empty
maximum = max([5, 2, 8, 1]) # 8

# min(iterable, default=None): Returns the minimum element in the list or an iterable, or a


default value if the list is empty
minimum = min([5, 2, 8, 1]) # 1
# sum(iterable, start=0): Returns the sum of all elements in the list or an iterable, with
an optional starting value
total = sum([1, 2, 3, 4]) # 10

# all(iterable): Returns True if all elements in the list or an iterable are True,
otherwise False
are_all_true = all([True, True, False]) # False

# any(iterable): Returns True if at least one element in the list or an iterable is True,
otherwise False
is_any_true = any([False, False, True]) # True

# sorted(iterable, key=None, reverse=False): Returns a new sorted list from the elements of
the list or an iterable, with optional key and reverse parameters
sorted_list = sorted([3, 1, 5, 2, 4]) # [1, 2, 3, 4, 5]

# enumerate(iterable, start=0): Returns an iterator that generates pairs of index and value
for each element in the list or an iterable
for index, value in enumerate(['a', 'b', 'c'], start=1):
print(index, value)
# Output: 1 a, 2 b, 3 c

# filter(function, iterable): Returns an iterator that filters elements from the list or an
iterable based on the provided function
filtered_list = list(filter(lambda x: x > 2, [1, 2, 3, 4, 5])) # [3, 4, 5]

# map(function, iterable): Applies the provided function to each element of the list or an
iterable and returns an iterator with the results
mapped_list = list(map(lambda x: x * 2, [1, 2, 3, 4])) # [2, 4, 6, 8]

# reversed(sequence): Returns an iterator that iterates over the elements of the list or a
sequence in reverse order
reversed_list = list(reversed([1, 2, 3, 4])) # [4, 3, 2, 1]

# zip(*iterables): Returns an iterator that combines elements from multiple iterables into
tuples
zipped_list = list(zip([1, 2, 3], ['a', 'b', 'c'])) # [(1, 'a'), (2, 'b'), (3, 'c')]

# slice(start, stop, step): Returns a slice object that represents a portion of the list
sliced_list = [1, 2, 3, 4, 5]
my_slice = sliced_list[1:4:2] # [2, 4]

# split(sep=None, maxsplit=-1): Splits a string into a list of substrings based on a


separator, with an optional maximum number of splits
my_string = "Hello, World!"
split_list = my_string.split(",") # ['Hello', ' World!']
Dict
# Sample dictionary
my_dict = {"name": "John", "age": 30, "city": "New York"}

# copy(): Returns a shallow copy of the dictionary


copied_dict = my_dict.copy() # {"name": "John", "age": 30, "city": "New York"}

# clear(): Removes all key-value pairs from the dictionary


my_dict.clear() # {}

# fromkeys(iterable, value=None): Creates a new dictionary with keys from an iterable and
values set to a specified value
new_dict = dict.fromkeys(["name", "age", "city"], None) # {'name': None, 'age': None,
'city': None}

# get(key, default=None): Returns the value associated with a specified key, or a default
value if the key is not found
value = my_dict.get("name", "Unknown") # 'John'

# items(): Returns a view object that contains key-value pairs of the dictionary
items = my_dict.items() # [('name', 'John'), ('age', 30), ('city', 'New York')]

# keys(): Returns a view object that contains the keys of the dictionary
keys = my_dict.keys() # ['name', 'age', 'city']

# values(): Returns a view object that contains the values of the dictionary
values = my_dict.values() # ['John', 30, 'New York']

# pop(key, default=None): Removes and returns the value associated with a specified key, or
a default value if the key is not found
removed_value = my_dict.pop("age") # 30

# popitem(): Removes and returns the last inserted key-value pair as a tuple
removed_item = my_dict.popitem() # ('city', 'New York')

# setdefault(key, default=None): Returns the value associated with a specified key, or


inserts the key-value pair with a default value if the key is not found
value = my_dict.setdefault("name", "Unknown") # 'John'

# update(iterable, **kwargs): Updates the dictionary with key-value pairs from an iterable
or keyword arguments
my_dict.update({"age": 35, "city": "London"}) # {'name': 'John', 'age': 35, 'city':
'London'}

# len(dict): Returns the number of key-value pairs in the dictionary


length = len(my_dict) # 3

# sorted(): Returns a new dictionary with sorted keys


sorted_dict = sorted(my_dict) # ['age', 'city', 'name']

# in: Checks if a specified key is present in the dictionary


is_present = "age" in my_dict # True
Set
# Create a new set.
s = set()

# Add an element to the set.


s.add(1)
# Output: {1}

# Remove all elements from the set.


s.clear()
# Output: set()

# Create a shallow copy of the set.


s1 = {1, 2, 3}
s2 = s1.copy()
# Output: {1, 2, 3}

# Return the difference between two sets.


s1 = {1, 2, 3}
s2 = {2, 3, 4}
diff = s1.difference(s2)
# Output: {1}

# Remove elements from the set that are also present in another set.
s1.difference_update(s2)
# Now s1 is updated to: {1}

# Remove an element from the set if it is present.


s = {1, 2, 3}
s.discard(2)
# Output: {1, 3}

# Return the intersection of two sets.


s1 = {1, 2, 3}
s2 = {2, 3, 4}
intersection = s1.intersection(s2)
# Output: {2, 3}

# Update the set with the intersection of itself and another set.
s1.intersection_update(s2)
# Now s1 is updated to: {2, 3}

# Check if the set has no common elements with another set.


s1 = {1, 2, 3}
s2 = {4, 5, 6}
is_disjoint = s1.isdisjoint(s2)
# Output: True

# Check if every element in the set is present in another set.


s1 = {1, 2}
s2 = {1, 2, 3, 4}
is_subset = s1.issubset(s2)
# Output: True
# Check if every element in another set is present in the set.
s1 = {1, 2, 3, 4}
s2 = {1, 2}
is_superset = s1.issuperset(s2)
# Output: True

# Remove and return an arbitrary element from the set.


s = {1, 2, 3}
element = s.pop()
# Output: 1
# s is updated to: {2, 3}

# Remove an element from the set. Raises a KeyError if the element is not found.
s = {1, 2, 3}
s.remove(2)
# Output: {1, 3}

# Return the symmetric difference between two sets.


s1 = {1, 2, 3}
s2 = {2, 3, 4}
symmetric_diff = s1.symmetric_difference(s2)
# Output: {1, 4}

# Update the set with the symmetric difference of itself and another set.
s1.symmetric_difference_update(s2)
# Now s1 is updated to: {1, 4}

# Return the union of two sets.


s1 = {1, 2, 3}
s2 = {3, 4, 5}
union = s1.union(s2)
# Output: {1, 2, 3, 4, 5}

# Update the set with the union of itself and another set.
s1.update(s2)
# Now s1 is updated to: {1, 2, 3, 4, 5}

You might also like