Python Basics: Strings, Lists, Dicts, Functions

Kind of Cheat Sheet for anything basic, that I did not know, have not used or interesting things, that good to know. I will keep it handy for a quick reference.

I am going to create separate posts for some Python features.

Strings

# Good to know, one time I fixed it using list and capitalize function:))
>>> name = "aAa bbB"
>>> print(name.title())
Aaa Bbb
>>> print(name.upper())
AAA BBB
>>> print(name.lower())
aaa bbb

#Adding Whitespace to Strings with Tabs or Newlines
>>> print("Item 1\n\tItem1.1\n\tItem1.2")
Item 1
        Item1.1
        Item1.2

# Always need this, to prepare data for further manipulations
>>> name = "   whitespaces   "
>>> name.rstrip()
'   whitespaces'
>>> name.lstrip()
'whitespaces   '
>>> name.strip()
'whitespaces'

# Way to change/insert something into the immutable string
>>> l = '12346789'
>>> l = l[:4] + '5' + l[4:]
>>> l
'123456789'

# string.find - return the index of first letter occurrence
start = 0   #start from the first
while start < len(string):
   flag = string.find(substring, start) # returned the index of first
   if flag != -1:
     start = flag
     count += 1
   else:
      # flag = -1 => no more substrings
      return count

Lists

# Last element
>>> l = ['aaa', 'bbb', 'ccc']
>>> l[-1]
'ccc'

# Change element with index
>>> l[0] = 'ddd'
>>> l
['ddd', 'bbb', 'ccc']

# Inserting Elements into a List
>>> l.insert(0, 'aaa')
>>> l
['aaa', 'ddd', 'bbb', 'ccc']

# Remove element by index
>>> del l[1]
>>> l
['aaa', 'bbb', 'ccc']

# Remove element with pop if need to use removed element after pop
# pop() - last element
# pop(index)
>>> popped_l=l.pop(2)
>>> l
['aaa', 'bbb']
>>> popped_l
'ccc'

# Remove element by name -> remove (only the first occurrence of the value you specify)
>>> removed_l = l.remove('aaa')
>>> l
['bbb']

# To remove all 2 from the list - while loop with remove in it:
>>> l = [1, 2, 3, 1, 2, 2, 3, 4, 5]
>>> l
[1, 2, 3, 1, 2, 2, 3, 4, 5]
>>> while 2 in l:
...     l.remove(2)
...
>>> l
[1, 3, 1, 3, 4, 5]

# Sort() - sort and permanently change the list, no way to revert
# l.sort(reverse=True) - reverse alphabetical order
>>> l = ['bbb', 'aaa', 'ccc', 'ddd']
>>> l.sort()
>>> l
['aaa', 'bbb', 'ccc', 'ddd']

# Need Temporarily - sorted()
>>> l
['bbb', 'aaa', 'ccc', 'ddd']
>>> print(sorted(l))
['aaa', 'bbb', 'ccc', 'ddd']
>>> l
['bbb', 'aaa', 'ccc', 'ddd']

# Reverse Order
>>> l
['ddd', 'ccc', 'aaa', 'bbb']
>>> l.reverse()
>>> l
['bbb', 'aaa', 'ccc', 'ddd']
>>> l.reverse()
>>> l
['ddd', 'ccc', 'aaa', 'bbb']

# Range, step and even numbers
>>> even_numbers = list(range(2,11,2))
>>> print(even_numbers)
[2, 4, 6, 8, 10]
>>> min(even_numbers)
2
>>> max(even_numbers)
10
>>> sum(even_numbers)
30


#List Comprehensions
>>> squares = [value**2 for value in range(1,11)]
>>> print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

or

>>> squares = []
>>> for value in range(1,11):
...     squares.append(value**2)
...
>>> print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# Copy list, l = l_copy will create just var to the same list
>>> l
['ddd', 'ccc', 'aaa', 'bbb']
>>> l_copy = l[:]
>>> l
['ddd', 'ccc', 'aaa', 'bbb']
>>> l_copy
['ddd', 'ccc', 'aaa', 'bbb']
>>> l_copy.append('eee')
>>> l
['ddd', 'ccc', 'aaa', 'bbb']
>>> l_copy
['ddd', 'ccc', 'aaa', 'bbb', 'eee']

Dictionaries

# Add and remove key pairs
>>> dict = {'k1': 'val1', 'k2': 'val2'}
>>> dict['k3'] = 'val3'
>>> dict
{'k1': 'val1', 'k2': 'val2', 'k3': 'val3'}
>>> del dict['k2']
>>> dict
{'k1': 'val1', 'k3': 'val3'}'

# Loop through all keys, values, items
>>> print(dict.items())
dict_items([('k1', 'val1'), ('k3', 'val3')])
>>> print(dict.keys())
dict_keys(['k1', 'k3'])
>>> print(dict.values())
dict_values(['val1', 'val3'])

>>> for key, value in dict.items():
...     print("Key: " + key)
...     print("Value: " + value)
Key: k1
Value: val1
Key: k3
Value: val3

Functions

# Positioning argumetns + default Values
>>> def func (arg1, arg2='ccc'):
...     print(f"{arg1} and {arg2}")
...
>>> func('aaa', 'bbb')
aaa and bbb
>>> func('aaa')
aaa and ccc

# Keyword Arguments
>>> func(arg2 = 'aaa', arg1 = 'bbb')
bbb and aaa

# Passing an Arbitrary Number of Arguments - *args=> empty tuple called args
>>> def func(*args):
...     print(args)
>>> func(1)
(1,)
>>> func(1, 2)
(1, 2)
>>> func(1, 2, 3)
(1, 2, 3)

# Using Arbitrary Keyword Arguments - **kargs
>>> def func(name, last, **info):
...     profile = {}
...     profile['first'] = name
...     profile['last'] = last
...     for key, value in info.items():
...             profile[key] = value
...     return profile
>>> user = func('Dmitry', 'Golovach' , location='CA')
>>> print(user)
{'first': 'Dmitry', 'last': 'Golovach', 'location': 'CA'}
>>> user = func('Dmitry', 'Golovach')
>>> print(user)
{'first': 'Dmitry', 'last': 'Golovach'}
Share

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *