[go: up one dir, main page]

0% found this document useful (0 votes)
7 views10 pages

C12CSCS

The document provides an overview of Python's built-in data types: lists, tuples, sets, and dictionaries. It explains how to create, manipulate, and perform various operations on these data types, including accessing elements, adding/removing items, and using comprehensions. Each section includes examples to illustrate the functionality of each data type.

Uploaded by

tnplpsbatch6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views10 pages

C12CSCS

The document provides an overview of Python's built-in data types: lists, tuples, sets, and dictionaries. It explains how to create, manipulate, and perform various operations on these data types, including accessing elements, adding/removing items, and using comprehensions. Each section includes examples to illustrate the functionality of each data type.

Uploaded by

tnplpsbatch6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

List

Lists are one of the built-in data types in Python used to store multiple values in a single variable. List items are
ordered, mutable, and allow duplicate values.

1. Creating a List: Create a list using square brackets.


Example: fruits = [“apple”, “banana”, “cherry”]

2. Creating an Empty List: Create an empty list.


Example: empty_list = []

3. list(iterable): Create a list from an iterable (e.g., string, tuple).


Example: my_list = list(“hello”) → my_list becomes [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

4. Accessing Elements: Access an item by its index (0-based).


Example: first_fruit = fruits[0] → first_fruit is “apple”

5. Slicing: Access a range of items.


Example: some_fruits = fruits[1:3] → some_fruits is [“banana”, “cherry”]

6. Negative Indexing: Access items from the end of the list.


Example: last_fruit = fruits[-1] → last_fruit is “cherry”

7. append(item): Adds an item to the end of the list.


Example: fruits.append(“orange”) → fruits becomes [“apple”, “banana”, “cherry”, “orange”]

8. extend(iterable): Adds items from an iterable to the end of the list.


Example: fruits.extend([“grape”, “kiwi”]) → fruits becomes [“apple”, “banana”, “cherry”, “orange”, “grape”, “kiwi”]

9. insert(index, item): Inserts an item at a specified index.


Example: fruits.insert(1, “mango”) → fruits becomes [“apple”, “mango”, “banana”, “cherry”, “orange”]

10. remove(item): Removes the first occurrence of the specified item.


Example: fruits.remove(“banana”) → fruits becomes [“apple”, “mango”, “cherry”, “orange”]
11. pop(index): Removes and returns the item at the specified index (or the last item if no index is specified).
Example: last_fruit = fruits.pop() → last_fruit is “orange”; fruits becomes [“apple”, “mango”, “cherry”]

12. clear(): Removes all items from the list.


Example: fruits.clear() → fruits becomes []

13. index(item): Returns the index of the first occurrence of the specified item.
Example: mango_index = fruits.index(“mango”) → mango_index is 1

14. count(item): Returns the number of times the specified item appears in the list.
Example: count_apple = fruits.count(“apple”) → count_apple is 1

15. sort(): Sorts the items in ascending order (modifies the original list).
Example: fruits.sort() → fruits becomes sorted alphabetically

16. reverse(): Reverses the order of the items in the list (modifies the original list).
Example: fruits.reverse() → fruits becomes reversed

17. copy(): Returns a shallow copy of the list.


Example: fruits_copy = fruits.copy() → fruits_copy is a new list with the same items as fruits

18. join(separator): Joins elements of a list into a single string (using a string method).
Example: joined_fruits = “, “.join(fruits) → “apple, mango, cherry”

19. slice(start, end): Access a range of items in the list.


Example: some_fruits = fruits[1:3] → some_fruits is [“mango”, “cherry”]

20. List Comprehensions: A concise way to create lists.


Example: squared = [x**2 for x in range(10)] → squared becomes [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

21. Concatenation: Combine two or more lists.


Example: combined = fruits + [“pear”, “peach”] → combined becomes [“apple”, “mango”, “cherry”, “pear”, “peach”]

22. Repetition: Repeat a list multiple times.


Example: repeated = [“apple”] * 3 → repeated becomes [“apple”, “apple”, “apple”]
23. Membership Testing: Check if an item exists in the list.
Example: is_apple_present = “apple” in fruits → is_apple_present is True

24. Finding the Length: Get the number of items in the list.
Example: length = len(fruits) → length is 4

25. Removing Duplicates: Use a set to remove duplicates.


Example: unique_fruits = list(set(fruits)) → unique_fruits contains unique items only

26. Nested Lists: Lists can contain other lists.


Example: nested = [[1, 2, 3], [4, 5, 6]] → Accessing items: nested[0][1] → 2

Tuple

Tuple is a collection which is ordered, unchangeable and allow duplicates.

1. Creating a Tuple: Create a tuple using parentheses


Example: my_tuple = (1, 2, 3)

2. Creating an Empty Tuple: Create an empty tuple


Example: empty_tuple = ()

3. Creating a Single-Element Tuple: Use a comma after the single element


Example: single_element_tuple = (5,)

4. Accessing Elements: Access an item by its index (0-based)


Example: first_element = my_tuple[0] → first_element is 1

5. Slicing: Access a range of items


Example: sliced_tuple = my_tuple[1:3] → sliced_tuple is (2, 3)

6. Negative Indexing: Access items from the end of the tuple


Example: last_element = my_tuple[-1] → last_element is 3

7. Concatenation: Combine tuples using the + operator


Example: new_tuple = my_tuple + (4, 5) → new_tuple is (1, 2, 3, 4, 5)
8. Repetition: Repeat a tuple using the * operator
Example: repeated_tuple = my_tuple * 2 → repeated_tuple is (1, 2, 3, 1, 2, 3)

9. Membership Testing: Check if an item exists in the tuple


Example: exists = 2 in my_tuple → exists is True

10. Finding the Length: Get the number of items using len()
Example: length = len(my_tuple) → length is 3

11. Count: Count the occurrences of a value


Example: count_of_twos = my_tuple.count(2) → count_of_twos is 1

12. Index: Find the first index of a value


Example: index_of_two = my_tuple.index(2) → index_of_two is 1

13. Tuple Unpacking: Assign values to variables in one line


Example: a, b, c = my_tuple → a is 1, b is 2, c is 3

14. Nested Tuples: Tuples can contain other tuples


Example: nested_tuple = ((1, 2), (3, 4)) → Accessing items: nested_tuple[0][1] → 2

15. Tuples are Immutable: You cannot modify, add, or remove elements once created
Example: my_tuple[1] = 10 # This will raise a TypeError

16. Deleting a Tuple: Use the del statement to delete a tuple


Example: del my_tuple → my_tuple is now deleted

17. Joining Tuples: Combine tuples with the + operator


Example: combined = (1, 2) + (3, 4) → combined is (1, 2, 3, 4)

18. Convert to List: Convert a tuple to a list using list()


Example: my_list = list(my_tuple) → my_list is [1, 2, 3]

19. Convert to String: Join elements of a tuple into a single string


Example: joined = “, “.join(map(str, my_tuple)) → joined is “1, 2, 3”
20. Creating Tuples with Generators: Create a tuple from a generator expression
Example: squared_tuple = tuple(x**2 for x in range(5)) → squared_tuple is (0, 1, 4, 9, 16)

21. Repetition: Repeat a tuple multiple times


Example: repeated = (1,) * 3 → repeated is (1, 1, 1)

22. Membership Testing: Check if an item exists in the tuple


Example: is_one_present = 1 in my_tuple → is_one_present is True

23. Count: Occurrences Count how many times an item appears


Example: count_ones = my_tuple.count(1) → count_ones is 1

24. Accessing Nested Tuples: Access items in nested tuples


Example: nested_tuple = ((1, 2), (3, 4)); item = nested_tuple[1][0] → item is 3

25. Creating Tuples with zip(): Combine lists into a tuple of pairs
Example: paired = tuple(zip([1, 2], [‘a’, ‘b’])) → paired is ((1, ‘a’), (2, ‘b’))

Sets:

Set is a collection is unordered, not changeable and duplicates not allowed.

1. Creating a Set: Create a set using curly braces


Example: my_set = {1, 2, 3}

2. Creating an Empty Set: Create an empty set


Example: empty_set = set()

3. Creating a Set from a List: Create a set from a list or iterable


Example: my_set = set([1, 2, 3]) → my_set is {1, 2, 3}

4. Accessing Elements: Sets are unordered and do not support indexing


Example: item = next(iter(my_set)) → item is one of the elements in my_set

5. Adding Elements: Add a single element to a set using add()


Example: my_set.add(4) → my_set becomes {1, 2, 3, 4}
6. Updating a Set: Add multiple elements using update()
Example: my_set.update([5, 6]) → my_set becomes {1, 2, 3, 4, 5, 6}

7. Removing Elements: Remove an element using remove()


Example: my_set.remove(2) → my_set becomes {1, 3, 4, 5, 6}
Note: Raises KeyError if the element is not found

8. Discarding Elements: Remove an element using discard()


Example: my_set.discard(3) → my_set becomes {1, 4, 5, 6}
Note: Does not raise an error if the element is not found

9. Popping an Element: Remove and return an arbitrary element using pop()


Example: popped_item = my_set.pop() → my_set is modified

10. Clearing a Set: Remove all elements using clear()


Example: my_set.clear() → my_set becomes set()

11. Membership Testing: Check if an item exists in the set


Example: exists = 1 in my_set → exists is True

12. Finding the Length: Get the number of items using len()
Example: length = len(my_set) → length is the count of elements

13. Union: Combine two sets using union() or the | operator


Example 1: new_set = my_set.union({7, 8}) → new_set is {1, 4, 5, 6, 7, 8}
Example 2: new_set = my_set | {7, 8} → same result

14. Intersection: Find common elements using intersection() or the & operator
Example 1: common_set = my_set.intersection({4, 5, 10}) → common_set is {4, 5}
Example 2: common_set = my_set & {4, 5, 10} → same result

15. Difference: Find elements in one set but not in another using difference() or the — operator
Example 1: diff_set = my_set.difference({5, 10}) → diff_set is {1, 4}
Example 2: diff_set = my_set — {5, 10} → same result
16. Symmetric Difference: Find elements in either set but not both using symmetric_difference() or the ^ operator
Example 1: sym_diff_set = my_set.symmetric_difference({1, 10}) → sym_diff_set is {4, 5, 10}
Example 2: sym_diff_set = my_set ^ {1, 10} → same result

17. Set Intersection Update: Modify a set to keep only elements found in another set using intersection_update()
Example: my_set.intersection_update({1, 2, 3}) → my_set becomes {1}

18. Set Difference Update: Modify a set to remove elements found in another set using difference_update()
Example: my_set.difference_update({1}) → my_set becomes set()

19. Set Symmetric Difference: Update Modify a set to keep only elements found in either set but not both using
symmetric_difference_update()
Example: my_set.symmetric_difference_update({2, 3}) → my_set becomes {2, 3}

20. Subset Check: if a set is a subset of another using issubset()


Example: is_subset = my_set.issubset({1, 2, 3, 4}) → is_subset is True

21. Superset Check: if a set is a superset of another using issuperset()


Example: is_superset = my_set.issuperset({1, 4}) → is_superset is True

22. Disjoint Sets: Check if two sets have no elements in common using isdisjoint()
Example: are_disjoint = my_set.isdisjoint({7, 8}) → are_disjoint is True

23. Copying a Set: Create a shallow copy of a set using copy()


Example: my_set_copy = my_set.copy() → my_set_copy is a new set with the same elements

24. Converting to a Set: Convert a list or other iterable to a set


Example: my_set = set([1, 2, 2, 3]) → my_set becomes {1, 2, 3}

25. Set Comprehensions: Create a set using a comprehension


Example: squared_set = {x**2 for x in range(5)} → squared_set is {0, 1, 4, 9, 16}

Dictionary:

Dictionary is one of the built-in datatype that allows us to store data in key-value pair which is unordered and mutable.
1. Creating a Dictionary: Create a dictionary using curly braces
Example: my_dict = {“key1”: “value1”, “key2”: “value2”}

2. Creating an Empty Dictionary: Create an empty dictionary


Example: empty_dict = {}

3. Accessing Values: Get a value by its key


Example: value = my_dict[“key1”] → value is “value1”

4. Adding or Updating Values: Add a new key-value pair or update an existing key
Example: my_dict[“key3”] = “value3” → my_dict becomes {“key1”: “value1”, “key2”: “value2”, “key3”: “value3”}

5. Removing a Key-Value Pair: Remove a key-value pair using del


Example: del my_dict[“key2”] → my_dict becomes {“key1”: “value1”, “key3”: “value3”}

6. Popping a Key-Value Pair: Remove and return a value using pop()


Example: value = my_dict.pop(“key1”) → my_dict becomes {“key3”: “value3”}

7. Clearing a Dictionary: Remove all key-value pairs using clear()


Example: my_dict.clear() → my_dict becomes {}

8. Checking for a Key: Check if a key exists using in


Example: exists = “key1” in my_dict → exists is True

9. Getting the Length: Get the number of key-value pairs using len()
Example: length = len(my_dict) → length is the count of pairs

10. Getting Keys: Get all keys using keys()


Example: keys = my_dict.keys() → keys is a view of all keys

11. Getting Values: Get all values using values()


Example: values = my_dict.values() → values is a view of all values

12. Getting Items: Get all key-value pairs using items()


Example: items = my_dict.items() → items is a view of all key-value pairs
13. Copying a Dictionary: Create a shallow copy using copy()
Example: my_dict_copy = my_dict.copy() → my_dict_copy is a new dictionary with the same items

14. Merging Dictionaries: Merge two dictionaries using update()


Example: my_dict.update({“key4”: “value4”}) → adds key4 to my_dict

15. Dictionary Comprehension: Create a dictionary using a comprehension


Example: squared_dict = {x: x**2 for x in range(5)} → squared_dict is {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

16. Nested Dictionaries: Dictionaries can contain other dictionaries


Example: nested_dict = {“outer”: {“inner”: “value”}} → Accessing: nested_dict[“outer”][“inner”] → “value”

17. Default Values: Use get() to return a value with a default if the key is not found
Example: value = my_dict.get(“key5”, “default”) → value is “default”

18. Popitem: Remove and return the last inserted key-value pair using popitem()
Example: last_item = my_dict.popitem() → my_dict is modified

19. Dictionary from Keys: Create a dictionary with keys from an iterable and a default value
Example: new_dict = dict.fromkeys([“a”, “b”, “c”], 0) → new_dict is {“a”: 0, “b”: 0, “c”: 0}

20. Updating Multiple Keys: Update multiple key-value pairs at once


Example: my_dict.update({“key1”: “new_value”, “key3”: “new_value”}) → updates specified keys

21. Iterating Over Keys :Loop through keys in a dictionary


Example: for key in my_dict: print(key)

22. Iterating Over Values: Loop through values in a dictionary


Example: for value in my_dict.values(): print(value)

23. Iterating Over Items: Loop through key-value pairs in a dictionary


Example: for key, value in my_dict.items(): print(key, value)

24. Finding Key Index: Use next() with an iterator to find the index of a key
Example: index = next((i for i, k in enumerate(my_dict) if k == “key1”), None)
25. Converting to List: Convert keys, values, or items to a list
Example: keys_list = list(my_dict.keys()) → keys_list contains the keys of my_dict

Summary

 Lists are great for storing ordered collections and can be easily changed.

 Tuples are perfect for when you need fixed data that shouldn’t change.

 Sets are used for unique items and are great for doing math operations with groups.

 Dictionaries help you store information in key-value pairs, making it easy to find what you need.

You might also like