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

Document (10) python

The document provides a comprehensive overview of basic data structures in Python, including lists, tuples, sets, dictionaries, and strings. It explains key operations such as accessing, modifying, and iterating through these data structures, along with examples of their usage. Each section includes code snippets demonstrating the functionality and methods associated with each data type.

Uploaded by

jiveriajabeen
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

Document (10) python

The document provides a comprehensive overview of basic data structures in Python, including lists, tuples, sets, dictionaries, and strings. It explains key operations such as accessing, modifying, and iterating through these data structures, along with examples of their usage. Each section includes code snippets demonstrating the functionality and methods associated with each data type.

Uploaded by

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

# Create a list

My_list = [1, 2, 3, 4, 5]

Print(“Original list:”, my_list)

# Access elements by index

First_element = my_list[0]

Last_element = my_list[-1]

Print(“First element:”, first_element)

Print(“Last element:”, last_element)

# Modify elements by index

My_list[2] = 10

Print(“List after modifying the 3rd element (index 2):”, my_list)

# Append an element at the end

My_list.append(6)

Print(“List after appending 6:”, my_list)

# Insert an element at a specific index

My_list.insert(2, 7) # Insert 7 at index 2

Print(“List after inserting 7 at index 2:”, my_list)

# Remove a specific element by value

My_list.remove(4)

Print(“List after removing element 4:”, my_list)

# Remove an element by index (pop)

Popped_element = my_list.pop(3) # Remove the element at index 3

Print(“List after popping the element at index 3:”, my_list)


Print(“Popped element:”, popped_element)

# Find the index of an element

Index_of_7 = my_list.index(7)

Print(“Index of element 7:”, index_of_7)

# Sort the list

My_list.sort()

Print(“List after sorting:”, my_list)

# Reverse the list

My_list.reverse()

Print(“List after reversing:”, my_list)

# Get the length of the list

Length_of_list = len(my_list)

Print(“Length of the list:”, length_of_list)

# Clear the list

My_list.clear()

Print(“List after clearing:”, my_list)

Output:

Original list: [1, 2, 3, 4, 5]

First element: 1

Last element: 5

List after modifying the 3rd element (index 2): [1, 2, 10, 4, 5]

List after appending 6: [1, 2, 10, 4, 5, 6]

List after inserting 7 at index 2: [1, 2, 7, 10, 4, 5, 6]


List after removing element 4: [1, 2, 7, 10, 5, 6]

List after popping the element at index 3: [1, 2, 7, 5, 6]

Popped element: 10

Index of element 7: 2

List after sorting: [1, 2, 5, 6, 7]

List after reversing: [7, 6, 5, 2, 1]

Length of the list: 5

List after clearing: []

# Tuple creation

My_tuple = (10, 20, 30, 40, 50)

# 1. Accessing elements in a tuple (indexing)

Print(“Element at index 0:”, my_tuple[0]) # Output: 10

Print(“Element at index 3:”, my_tuple[3]) # Output: 40

# 2. Slicing a tuple

Print(“Sliced tuple (from index 1 to 3):”, my_tuple[1:4]) # Output: (20, 30,


40)

# 3. Iterating through a tuple

Print(“Iterating over the tuple:”)

For element in my_tuple:

Print(element)

# 4. Checking if an element exists in a tuple

If 30 in my_tuple:

Print(“30 is in the tuple”)


# 5. Tuple length

Print(“Length of the tuple:”, len(my_tuple)) # Output: 5

# 6. Concatenating two tuples

Another_tuple = (60, 70)

New_tuple = my_tuple + another_tuple

Print(“Concatenated tuple:”, new_tuple) # Output: (10, 20, 30, 40, 50, 60,
70)

# 7. Repeating a tuple

Repeated_tuple = my_tuple * 2

Print(“Repeated tuple:”, repeated_tuple) # Output: (10, 20, 30, 40, 50,


10, 20, 30, 40, 50)

# 8. Finding index of an element

Index_of_30 = my_tuple.index(30)

Print(“Index of element 30:”, index_of_30) # Output: 2

# 9. Counting occurrences of an element

Count_of_40 = my_tuple.count(40)

Print(“Count of element 40:”, count_of_40) # Output: 1

# 10. Unpacking a tuple into variables

A, b, c, d, e = my_tuple

Print(“Unpacked values:”, a, b, c, d, e) # Output: 10 20 30 40 50

Explanation of Key Operations:

Accessing elements: Tuples support indexing, so you can retrieve


elements by their index.

Slicing: You can slice a tuple to get a subset of its elements.


Iterating: You can iterate over the elements of a tuple using a loop.

Checking membership: The in keyword checks if a value exists in the


tuple.

Length: The len() function returns the number of elements in the tuple.

Concatenation: You can concatenate two tuples using the + operator.

Repetition: You can repeat a tuple multiple times using the * operator.

Finding index: The index() method returns the index of the first occurrence
of an element.

Counting occurrences: The count() method counts how many times a


value appears in the tuple.

Unpacking: You can unpack a tuple into individual variables.

Since tuples are immutable, operations like addition, repetition, and


slicing create new tuples without modifying the original.

Here’s a sample Python program that demonstrates all the key operations
of a set:

```python

# Set creation

My_set = {10, 20, 30, 40, 50}

# 1. Adding elements to a set

My_set.add(60)

Print(“After adding 60:”, my_set) # Output: {10, 20, 30, 40, 50, 60}

# 2. Removing elements from a set

My_set.remove(30) # Raises KeyError if element is not found

Print(“After removing 30:”, my_set) # Output: {10, 20, 40, 50, 60}

# Using discard (does not raise an error if element is not found)

My_set.discard(70) # Element 70 does not exist but no error is raised


Print(“After discarding 70 (non-existent):”, my_set)

# 3. Checking membership

Print(“Is 40 in my_set?”, 40 in my_set) # Output: True

Print(“Is 100 in my_set?”, 100 in my_set) # Output: False

# 4. Set union

Another_set = {50, 60, 70, 80}

Union_set = my_set.union(another_set)

Print(“Union of my_set and another_set:”, union_set) # Output: {10, 20,


40, 50, 60, 70, 80}

# 5. Set intersection

Intersection_set = my_set.intersection(another_set)

Print(“Intersection of my_set and another_set:”, intersection_set) #


Output: {50, 60}

# 6. Set difference

Difference_set = my_set.difference(another_set)

Print(“Difference between my_set and another_set:”, difference_set) #


Output: {10, 20, 40}

# 7. Set symmetric difference

Sym_diff_set = my_set.symmetric_difference(another_set)

Print(“Symmetric difference between my_set and another_set:”,


sym_diff_set) # Output: {10, 20, 40, 70, 80}

# 8. Iterating over a set

Print(“Iterating over my_set:”)

For element in my_set:


Print(element)

# 9. Set length

Print(“Length of my_set:”, len(my_set)) # Output: 5

# 10. Clearing all elements from a set

My_set.clear()

Print(“After clearing my_set:”, my_set) # Output: set()

```

### Explanation of Key Operations:

1. **Adding elements**: The `add()` method inserts an element into the


set if it’s not already present.

2. **Removing elements**: The `remove()` method removes an element


from the set, raising a `KeyError` if the element is not found. The
`discard()` method does the same but without raising an error if the
element is not present.

3. **Checking membership**: The `in` keyword checks if an element


exists in the set.

4. **Set union**: The `union()` method returns a new set that contains all
elements from both sets (without duplicates).

5. **Set intersection**: The `intersection()` method returns a new set with


only the elements common to both sets.

6. **Set difference**: The `difference()` method returns a new set with


elements in the first set that are not in the second set.

7. **Symmetric difference**: The `symmetric_difference()` method returns


a new set with elements that are in either of the sets but not in both.

8. **Iterating**: You can iterate over the set using a loop.

9. **Length**: The `len()` function returns the number of elements in the


set.

10. **Clearing the set**: The `clear()` method removes all elements from
the set, leaving it empty.
Note: Since sets are unordered collections, the elements’ order during
iteration or when printed may vary.

Here’s a sample Python program that demonstrates all the key operations
of a dictionary:

```python

# Dictionary creation

My_dict = {

“name”: “Alice”,

“age”: 25,

“city”: “New York”

# 1. Accessing values by key

Print(“Name:”, my_dict[“name”]) # Output: Alice

Print(“Age:”, my_dict[“age”]) # Output: 25

# 2. Adding or updating key-value pairs

My_dict[“age”] = 26 # Update existing key

My_dict[“profession”] = “Engineer” # Add new key-value pair

Print(“Updated dictionary:”, my_dict)

# 3. Removing a key-value pair using pop()

Removed_value = my_dict.pop(“city”)

Print(“Removed ‘city’:”, removed_value) # Output: New York

Print(“Dictionary after pop:”, my_dict)

# 4. Removing the last inserted key-value pair using popitem()

Key, value = my_dict.popitem()


Print(f”Removed last item: {key} = {value}”) # Output: profession =
Engineer

Print(“Dictionary after popitem:”, my_dict)

# 5. Checking if a key exists in the dictionary

If “name” in my_dict:

Print(“Key ‘name’ exists in the dictionary”)

# 6. Getting a value using get()

Age = my_dict.get(“age”) # Returns 26

Print(“Age using get():”, age)

Non_existing_value = my_dict.get(“salary”, “Not Found”) # Returns


default value “Not Found”

Print(“Non-existing key ‘salary’:”, non_existing_value)

# 7. Iterating over keys

Print(“Iterating over keys:”)

For key in my_dict:

Print(key)

# 8. Iterating over values

Print(“Iterating over values:”)

For value in my_dict.values():

Print(value)

# 9. Iterating over key-value pairs

Print(“Iterating over key-value pairs:”)

For key, value in my_dict.items():

Print(f”{key} = {value}”)
# 10. Merging two dictionaries

Another_dict = {“country”: “USA”, “hobby”: “Photography”}

My_dict.update(another_dict)

Print(“Dictionary after merging with another_dict:”, my_dict)

# 11. Getting all keys

Keys = my_dict.keys()

Print(“All keys in the dictionary:”, keys)

# 12. Getting all values

Values = my_dict.values()

Print(“All values in the dictionary:”, values)

# 13. Getting all key-value pairs

Items = my_dict.items()

Print(“All key-value pairs in the dictionary:”, items)

# 14. Clearing the dictionary

My_dict.clear()

Print(“Dictionary after clearing:”, my_dict) # Output: {}

```

### Explanation of Key Operations:

1. **Accessing values by key**: You can access the value of a specific key
using the `my_dict[key]` syntax.

2. **Adding/updating key-value pairs**: You can add or update key-value


pairs by assigning a value to a key, `my_dict[key] = value`.

3. **Removing key-value pairs**: The `pop()` method removes a specific


key-value pair and returns the value. The `popitem()` method removes
and returns the last key-value pair added.
4. **Checking if a key exists**: You can check if a key exists in a dictionary
using the `in` keyword.

5. **Getting values safely**: The `get()` method retrieves the value for a
given key, and you can specify a default value if the key doesn’t exist.

6. **Iterating**: You can iterate over keys, values, or both key-value pairs
using `.keys()`, `.values()`, and `.items()`, respectively.

7. **Merging dictionaries**: The `update()` method merges another


dictionary into the current one.

8. **Getting all keys, values, or items**: You can retrieve all the keys,
values, or key-value pairs using `.keys()`, `.values()`, and `.items()`.

9. **Clearing the dictionary**: The `clear()` method removes all key-value


pairs from the dictionary.

This program illustrates the key functionalities and operations that you
can perform on dictionaries in Python.

Here’s a sample Python program that demonstrates all the key operations
for strings:

```python

# String creation

My_string = “Hello, World!”

# 1. Accessing characters (indexing)

Print(“Character at index 0:”, my_string[0]) # Output: H

Print(“Character at index 7:”, my_string[7]) # Output: W

# 2. Slicing a string

Print(“Slicing (from index 0 to 5):”, my_string[0:5]) # Output: Hello

Print(“Slicing (last 6 characters):”, my_string[-6:]) # Output: World!


# 3. String length

Print(“Length of the string:”, len(my_string)) # Output: 13

# 4. String concatenation

Greeting = “Hello”

Name = “Alice”

Full_greeting = greeting + “, “ + name + “!”

Print(“Concatenated string:”, full_greeting) # Output: Hello, Alice!

# 5. Iterating over a string

Print(“Iterating over my_string:”)

For char in my_string:

Print(char)

# 6. Checking membership

Print(“Is ‘World’ in my_string?”, “World” in my_string) # Output: True

Print(“Is ‘Python’ in my_string?”, “Python” in my_string) # Output: False

# 7. String case conversions

Print(“Uppercase:”, my_string.upper()) # Output: HELLO, WORLD!

Print(“Lowercase:”, my_string.lower()) # Output: hello, world!

# 8. Replacing substrings

New_string = my_string.replace(“World”, “Python”)

Print(“After replacement:”, new_string) # Output: Hello, Python!

# 9. Splitting a string

Words = my_string.split(“, “)

Print(“Split the string by ‘, ‘:”, words) # Output: [‘Hello’, ‘World!’]


# 10. Joining a list of strings into a single string

Words_to_join = [‘Hello’, ‘Python’]

Joined_string = “ “.join(words_to_join)

Print(“Joined string:”, joined_string) # Output: Hello Python

# 11. Stripping whitespace

Extra_spaces = “ Hello, World! “

Stripped_string = extra_spaces.strip()

Print(“String after stripping whitespace:”, stripped_string) # Output:


Hello, World!

# 12. Finding a substring

Position = my_string.find(“World”)

Print(“Position of ‘World’:”, position) # Output: 7

# 13. Counting occurrences of a substring

Count = my_string.count(“l”)

Print(“Count of ‘l’ in my_string:”, count) # Output: 3

# 14. Checking string starts/ends with a specific substring

Print(“Does my_string start with ‘Hello’?”, my_string.startswith(“Hello”)) #


Output: True

Print(“Does my_string end with ‘!’?”, my_string.endswith(“!”)) # Output:


True

```

### Explanation of Key Operations:


1. **Accessing characters**: Strings are indexed, so you can access
individual characters using their index.

2. **Slicing**: You can extract a portion of the string using slicing, which
works similarly to lists and tuples.

3. **Length**: The `len()` function returns the length of the string


(number of characters).

4. **Concatenation**: You can concatenate strings using the `+` operator.

5. **Iterating**: You can iterate through each character in a string using a


loop.

6. **Checking membership**: The `in` keyword checks if a substring


exists within the string.

7. **Case conversions**: The `upper()` and `lower()` methods convert a


string to uppercase and lowercase, respectively.

8. **Replacing substrings**: The `replace()` method replaces a substring


with another substring.

9. **Splitting**: The `split()` method splits the string into a list based on a
delimiter.

10. **Joining**: The `join()` method combines a list of strings into a single
string with a specified separator.

11. **Stripping whitespace**: The `strip()` method removes leading and


trailing spaces from a string.

12. **Finding a substring**: The `find()` method returns the index of the
first occurrence of a substring.

13. **Counting occurrences**: The `count()` method counts how many


times a substring occurs in the string.

14. **Checking starts/ends with**: The `startswith()` and `endswith()`


methods check if a string starts or ends with a specific substring.

Strings in Python are immutable, meaning that operations like


concatenation, slicing, and replacing return new strings without modifying
the original one.

You might also like