📜 ⬆️ ⬇️

Python: collections, part 3/4: combining collections, adding and removing items

Part 1Part 2Part 3Part 4
image We will continue to study the general principles of working with standard collections (it does not consider the collections module in it) Python. Will be considered ways to merge and update collections with the formation of a new or a change in the original, as well as ways to add and remove items in the modified collections.

For whom : for Python learners who already have an initial understanding of the collections and work with them, who want to systematize and deepen their knowledge, put them into a coherent picture.

Table of contents:


  1. Combining strings, tuples, lists, dictionaries without changing the source.
  2. Union of sets without changing the source.
  3. Combining a list, a dictionary and a mutable set with a change in the original collection.
  4. Adding and removing items from mutable collections.
  5. Features of work with a changeable and not changeable collection.

1. Combining strings, tuples, lists, dictionaries without changing the source


Consider ways to combine strings, tuples, lists, dictionaries without changing the original collections - when a new collection of the same type is created from several collections without changing the original ones.
')
  1. Combining strings and tuples (tuple) is possible using the addition operator "+"

    str1 = 'abc' str2 = 'de' str3 = str1 + str2 print(str3) # abcde tuple1 = (1, 2, 3) tuple2 = (4, 5) tuple3 = tuple1 + tuple2 print(tuple3) # (1, 2, 3, 4, 5) 

  2. To combine lists (list) there are three options without changing the original list:

    • We add all the elements of the second list to the elements of the first, (analogous method .extend () but without changing the original list):

       a = [1, 2, 3] b = [4, 5] c = a + b print(a, b, c) # [1, 2, 3] [4, 5] [1, 2, 3, 4, 5] 

    • Add the second list as one item without changing the source list (analogue of the method.append () but without changing the source list):

       a = [1, 2, 3] b = [4, 5] c = a + [b] print(a, b, c) # [1, 2, 3] [4, 5] [1, 2, 3, [4, 5]] 

  3. UPD: Method added by longclaps in the comments:

     a, b = [1, 2, 3], [4, 5] c = [*a, *b] #     3.5   print(c) # [1, 2, 3, 4, 5] 

  4. With a dictionary (dict), everything is not quite simple.

    Add two dictionaries to get the third operator + Python does not allow "TypeError: unsupported operand type (s) for +: 'dict' and 'dict'".

    You can do this in a different way by combining the .copy () and .update () methods:

     dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} dict3 = dict1.copy() dict3.update(dict2) print(dict3) # {'a': 1, 'c': 3, 'b': 2, 'd': 4} 

    In Python 3.5 a new more elegant way appeared:

     dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} dict3 = {**dict1, **dict2} print(dict3) # {'a': 1, 'c': 3, 'b': 2, 'd': 4} 

2. Combining sets without changing the source


For both types of sets (set, frozenset), different variants of the combination of sets are possible (the original sets do not change - a new set is returned).

image

 #     (    ) a = {'a', 'b'} b = { 'b', 'c'} #   b   

  1. Union :

     c = a.union(b) # c = b.union(a)     # c = a + b #    +   # TypeError: unsupported operand type(s) for +: 'set' and 'set' c = a | b #     print(c) # {'a', 'c', 'b'} 

  2. Intersection :

     c = a.intersection(b) # c = b.intersection(a)     c = a & b #     print(c) # {'b'} 

    The intersection of more than 2 sets at once:
     a = {'a', 'b'} b = { 'b', 'c'} c = { 'b', 'd'} d = a.intersection(b, c) #    d = set.intersection(a, b, c) #    ( ) print(d) # {'b'} 

  3. Difference (difference) - the result depends on how many of which we subtract:

     c = a.difference(b) # c = a - b        print(c) # {'a'} c = b.difference(a) # c = b - a        print(c) # {'c'} 

  4. Symmetric difference (symmetric_difference) This is a kind of operation opposite to the intersection - selects elements from both sets that do not intersect, that is, all but the same:

     c = b.symmetric_difference(a) # c = a.symmetric_difference(b) #     c = b ^ a #      print(c) # {'a', 'c'} 

3. Combining a list, a dictionary and a variable set with a change in the original collection


  1. For list

    • Add all the elements of the second list to the elements of the first with the change of the first list method. extend ():

       a.extend(b) # a += b  a.extend(b) print(a, b) # [1, 2, 3, 4, 5] [4, 5] 

    • Add the second list as one item with the change of the first list method. append ():

        a.append(b) # a += [b]  a.append(b) print(a, b) # [1, 2, 3, [4, 5]] [4, 5] 
  2. To change the dictionary with the addition of elements of another dictionary method is used. update ().

    Note: for matching dictionary keys, the values ​​are updated:

     dict1 = {'a': 1, 'b': 2} dict2 = {'a': 100, 'c': 3, 'd': 4} dict1.update(dict2) print(dict1) # {'a': 100, 'c': 3, 'b': 2, 'd': 4} 

  3. For a variable set (set), in addition to the operations described in the previous section, their analogs are also possible, but with a change in the original set — these methods end with _update. The result depends on how many are updated.

    • . difference_update ()

       a = {'a', 'b'} b = { 'b', 'c'} a.difference_update(b) print(a, b) # {'a'} {'b', 'c'} a = {'a', 'b'} b = { 'b', 'c'} b.difference_update(a) print(a, b) # {'a', 'b'} {'c'} 

    • . intersection_update ()

       a = {'a', 'b'} b = { 'b', 'c'} a.intersection_update(b) print(a, b) # {'b'} {'b', 'c'} a = {'a', 'b'} b = { 'b', 'c'} b.intersection_update(a) print(a, b) # {'b', 'a'} {'b'} 

    • . symmetric_difference_update ()

       a = {'a', 'b'} b = { 'b', 'c'} a.symmetric_difference_update(b) print(a, b) # {'c', 'a'} {'c', 'b'} a = {'a', 'b'} b = { 'b', 'c'} b.symmetric_difference_update(a) print(a, b) # {'a', 'b'} {'c', 'a'} 

    4 Adding and deleting items of mutable collections


    Adding and deleting items to a collection is possible only for mutable collections: a list (list), a set (only set, not frozenset), a dictionary (dict). Moreover, for a list that is an indexed collection, it is also important at what position we add an item.

    image

    Notes:

    • Examples of using the .insert method (index, element)
       my_list = [1, 2, 3] my_list.insert(0, 0) # index = 0 -    print(my_list) # [0, 1, 2, 3] my_list.insert(10, 4) #      -     print(my_list) # [0, 1, 2, 3, 4] my_list.insert(-10, -1) #       -    print(my_list) # [-1, 0, 1, 2, 3, 4] my_list = [1, 2, 3] my_list.insert(1, 1.5) #   1  2 (  !) #        ,        #     -   1   print(my_list) # [1, 1.5, 2, 3] 

    • Examples of using the del operator
       #    my_list = [1, 2, 3, 4, 5, 6, 7] del my_list[1] #     print(my_list) # [1, 3, 4, 5, 6, 7] del my_list[-3:-1] #     print(my_list) # [1, 3, 4, 7] # del my_list[10] # IndexError: list assignment index out of range #    my_dict = {'a': 1, 'b': 2, 'c': 3} del my_dict['b'] print(my_dict) # {'a': 1, 'c': 3} # del my_dict['z'] # KeyError      

    • Removing and adding list items with a slice is covered in the second article .

    • An example of how .append () and .extend () are discussed in the third chapter of this article .

    5 Features of work with a variable and not changeable collection


    1. A string is an immutable collection - if we change it - we create a new object!

       str1 = 'abc' print(str1, id(str1)) # abc 140234080454000 str1 += 'de' print(str1, id(str1)) # abcde 140234079974992 -   ,   id! 

      Sample code with two original identical strings.

       str1 = 'abc' str2 = str1 print(str1 is str2) # True -         ! str1 += 'de' #   str1    ! print(str1 is str2) # False -     ! print(str1, str2) # abcde abc -   

    2. We change the list and here we must be very careful not to make a serious mistake! Compare this example with the example with the lines above:

       list1 = [1, 2, 3] list2 = list1 print(list1 is list2) # True -         ! #   ,   : list1 += [4] print(list1, list2) # [1, 2, 3, 4] [1, 2, 3, 4] #    ,        ! 

      And if you need an independent copy , with which you can work separately?

       list1 = [1, 2, 3] list2 = list(list1) #    list3 = list1[:] #    list4 = list1.copy() #    -   Python 3.3+ print(id(list1), id(list2), id(list3), id(list4)) #  4 id ,      4   list1 += [4] #    print(list1, list2, list3, list4) # [1, 2, 3, 4] [1, 2, 3] [1, 2, 3] [1, 2, 3] #     -   ,      
    Part 1Part 2Part 3Part 4

    I invite you to discuss:


    • If I somewhere made an inaccuracy or did not take into account something important - write in the comments, important comments will later be added to the article indicating your authorship.
    • If some points are not clear and clarification is required - write your questions in the comments - or I or other readers will give an answer, and efficient questions with answers will be later added to the article.

Source: https://habr.com/ru/post/319876/


All Articles