list copy

inspired by How to clone or copy a list? in stackoverflow

clone_list = sample_list.copy()
  • or
    clone_list = sample_list[:]
    
  • or
    clone_list = list(sample_list)
    
  • or
    import copy
    clone_list = copy.copy(sample_list)
    
  • or

    import copy
    clone_list = copy.deepcopy(sample_list)
    
  • example:

    >>> id(x)
    4505979072
    >>> k = x
    >>> id(k)
    4505979072
    
    >>> k = x.copy()
    >>> id(k)
    4445208000
    >>> k = x[:]
    >>> id(k)
    4505977632
    >>> import copy
    >>> k = copy.copy(x)
    >>> id(k)
    4505754352
    >>> k = copy.deepcopy(x)
    >>> id(k)
    4505978352
    >>> k = x[:]
    >>> id(k)
    4506260896
    >>> k = copy.deepcopy(x)
    >>> id(k)
    4506261136
    

reverse list

sample_list[::-1]
  • example:
    >>> ['1', '2', '3', '4', '5'][::-1]
    ['5', '4', '3', '2', '1']
    

cast format (str -> int)

list( map(int, sample_list) )
  • example:
    >>> print( list( map(int, ['2', '8', '4', '127', 'HKD'][:3][::-1] ) ) )
    [4, 8, 2]
    

zip two lists

>> from itertools import zip_longest
>>> x = ['1', '2', '3', '4']
>>> y = ['one', 'two', 'three', 'four']
>>> for i, j in zip_longest( x, y ):
  print(i, j)

1 one
2 two
3 three
4 four
  • or zip to a map
    >>> x = ['1', '2', '3', '4']
    >>> y = ['one', 'two', 'three', 'four']
    >>> print( {key: value for key, value in zip_longest(x, y)} )
    {'1': 'one', '2': 'two', '3': 'three', '4': 'four'}
    

list mathematical

  • sum

    >>> n = ['1', '2', '3', '4']
    >>> print( sum( list( map(int, n) ) ) )
    10
    
  • multiplication python

Copyright © marslo 2020-2023 all right reserved,powered by GitbookLast Modified: 2024-05-16 01:41:37

results matching ""

    No results matching ""