Skip to content

Data Types

https://www.programiz.com/python-programming/methods

Strings:

To check if a string is empty:

>>> a = ''
>>> if not a:
...  print('string is empty')
...
string is empty
>>>str(6)     ## To convert number 6 as a string
'6'
>>>int('6')  ## To convert string to number
6
>>>repr(string)


>>> a='Hello'
>>> len(a)
5
>>> a[0]
'H'
>>> a[1:3]       # to display index 1 upto index 3, but not including 3
'el'
>>> a[-1]
'o'
>>> a[-2:]
'lo'
>>> a.swapcase()
'hELLO'


>>>a.find('l')
2
>>> a.startswith('H')
True
>>> a.endswith('i')
False
>>> 'l' in a
True
  • s.lower(), s.upper() -- returns the lowercase or uppercase version of the string
  • s.strip() -- returns a string with whitespace removed from the start and end
  • s.isalpha()/s.isdigit()/s.isspace()... -- tests if all the string chars are in the various character classes
  • s.startswith('other'), s.endswith('other') -- tests if the string starts or ends with the given other string
  • s.find('other') -- searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found
  • s.replace('old', 'new') -- returns a string where all occurrences of 'old' have been replaced by 'new'
  • s.split('delim') -- returns a list of substrings separated by the given delimiter. The delimiter is not a regular expression, it's just text. 'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb', 'ccc']. As a convenient special case s.split() (with no arguments) splits on all whitespace chars.
  • s.join(list) -- opposite of split(), joins the elements in the given list together using the string as the delimiter. e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc

Justifying Text with rjust(), ljust(), and center()

>>> 'Hello'.rjust(10)
'     Hello'
>>> 'Hello'.rjust(20, '*')
'***************Hello'
>>> 'Hello'.center(20, '=')
'=======Hello========'

Removing Whitespace with strip(), rstrip(), and lstrip()

>>> spam = '    Hello World     '
>>> spam.strip()
'Hello World'
>>> spam.lstrip()
'Hello World '
>>> spam.rstrip()
'    Hello World'


>>> "there are %d apples" %10
'there are 10 apples'


>>> 'Hi %s, I have %d donuts' % ('Jeeva', 20)
'Hi Jeeva, I have 20 donuts’

i18n Strings (Unicode)

Regular Python strings are not unicode, they are just plain bytes. To create a unicode string, use the 'u' prefix on the string literal:

ustring = u'A unicode \u018e string \xf1' ustring u'A unicode \u018e string \xf1’

LISTS:

https://docs.python.org/2/tutorial/datastructures.html

>>> a = [1, 2, 3, 4]
>>> 2 in a
True
>>> 5 in a
False


>>> del a   ### removes the variable or list a


b = [1, 2, 3, 4]
>>> del b[1]
>>> b
b = [1, 3, 4]


>>> a = [1,2,3,4]
>>> a.pop(0)
1
>>> a
[2, 3, 4]


>>> a=['Jeeva', 'Brinda', 'Abi', ‘Gautam']


>>> c=[a,b]  # to store two lists together
>>> c
[['Jeeva', 'Brinda', 'Abi', 'Gautam'], [1, 3, 4]]


>>> c[1]
[1, 3, 4]

Skip and reverse values:

>>> a=[1,2,3,4,5,6,7,8]
>>> a[::2]
[1, 3, 5, 7]
>>> a[::3]
[1, 4, 7]
>>> a[::-1]
[8, 7, 6, 5, 4, 3, 2, 1]
>>> a[::-2]
[8, 6, 4, 2]

Sorting:

>>> a
['Jeeva', 'Brin', 'Abi', 'Gautam']


>>> sorted(a)    ## to sort the list
['Abi', 'Brin', 'Gautam', ‘Jeeva']


>>> sorted(a, reverse=True)    ## to sort it in reverse order
['Jeeva', 'Gautam', 'Brin', 'Abi’]

Sort using key=function

>>> sorted(a, key=len)     ## To sort by len() function
['Abi', 'Brin', 'Jeeva', 'Gautam’]


To sort by the last character
>>> def Last(s): return s[-1]  ## define a function called Last to return the last
. . .                          ## character of the string


>>> sorted(a, key=Last)        ## Sort using Last function
['Jeeva', 'Abi', 'Gautam', 'Brin']

Sort by field:

rows = [[1, 2, 3], [1, 5, 6], [2, 3, 4]]
rows.sort(key=lambda x: x[1])   ## sort by index 1
>>> rows
[[1, 2, 3], [2, 3, 4], [1, 5, 6]]


from __future__ import print_function # (Only for python2)
for row in rows:
...  print(*row)
1 2 3
2 3 4
1 5 6


>>> b=[1, 3, 4]
>>> b.append(5)
>>> b
[1, 3, 4, 5]
>>> b.insert(1,2)
>>> b
[1, 2, 3, 4, 5]

To insert at the beginning:

list.insert(0, 'foo')

append vs extend:

>>> a = [1,2]
>>> a
[1, 2]
>>> a.append([1,2])
>>> a
[1, 2, [1, 2]]
>>> a.extend([1,2])
>>> a
[1, 2, [1, 2], 1, 2]

Join and Split of LISTS

>>> a
['Jeeva', 'Brin', 'Abi', 'Gautam']
>>> b = ':'.join(a)
>>> b
'Jeeva:Brin:Abi:Gautam'
>>> b.split(':')
['Jeeva', 'Brin', 'Abi', 'Gautam']


>>> a = ['Jeeva', 'Brin']
>>> b = ['Abi', 'Gautam']
>>> a + b
['Jeeva', 'Brin', 'Abi', 'Gautam']

List Comprehension:

List comprehensions provide a concise way to create lists.

  • It consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses.
  • The expressions can be anything, meaning you can put in all kinds of objects in lists.
  • The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
  • The list comprehension always returns a result list.

The basic Syntax is: [ expression for item in list if conditional ]

This is equivalent to:

for item in list:
    if conditional:
        expression
[x.lower() for x in ["A","B","C"]]
['a', 'b', 'c']
string = "Hello 12345 World"
numbers = [x for x in string if x.isdigit()]
numbers
['1', '2', '3', '4', '5']


A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A1 = range(10)
A2 = sorted([i for i in A1 if i in A0])
A3 = sorted([A0[s] for s in A0])
A4 = [i for i in A1 if i in A3]
A5 = {i:i*i for i in A1}
A6 = [[i,i*i] for i in A1]


A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} # the order may vary
A1 = range(0, 10) # or [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] in python 2
A2 = []
A3 = [1,2,3,4,5]
A4 = [1,2,3,4,5]
A5 = {0:0,1:1,2:4,3:9,4:16,5:25,6:36,7:49,8:64,9:81}
A6 = [[0,0], [1,1], [2,4], [3,9], [4,16], [5,25], [6,36], [7,49], [8,64], [9,81]]


doubled = [thing.func for thing in list_of_things]
images = [image.id for image in ec2.instances.all()]
print [ [ i, j] for i in range( x + 1) for j in range( y + 1) if ( ( i + j ) != n )]

To find if all numbers are positive in a list:

all([int(i)>0 for i in numbers])

To find if any one is palindrome

any([j == j[::-1] for j in stings])

Removing duplicate entries from Lists:

The common approach to get a unique collection of items is to use a set. Sets are unordered collections of distinct objects. To create a set from any iterable, you can simply pass it to the built-in set() function. If you later need a real list again, you can similarly pass the set to the list() function.

The following example should cover whatever you are trying to do:

>>> t = [1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> t
[1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> list(set(t))
[1, 2, 3, 5, 6, 7, 8]
>>> s = [1, 2, 3]
>>> list(set(t) - set(s))
[8, 5, 6, 7]

To count the number of occurrences of list value:

>>> a
[1, 2, 3, 2, 3, 4, 5]
>>> a.count(2)
2

Sets:

Sets are an unordered bag of unique values. A single set contains values of any immutable data type. There is no order associated with the elements of a set. Thus, it does not support indexing or slicing like we do with lists

https://www.programiz.com/python-programming/methods/set/copy

Creating sets

myset = {1, 2} # Directly assigning values to a set
myset = set()  # Initializing a set
myset = set(['a', 'b']) # Creating a set from a list
myset
{'a', 'b'}

The Python set union() method returns a new set with distinct elements from all the sets.

a = {2, 4, 5, 9}
b = {2, 4, 11, 12}
a.union(b) # Values which exist in a or b
{2, 4, 5, 9, 11, 12}

The intersection() method returns a new set with elements that are common to all sets.

a.intersection(b) # Values which exist in a and b
{2, 4}

set.intersection(a,b)
{2, 4}

The Python set union() method returns a new set with distinct elements from all the sets.

A = {2, 3, 5}
B = {1, 3, 5}
A.union(B)
{1, 2, 3, 5}

A.union(b) == B.union(a)
True

A.intersection(B) == B.intersection(A)
True

A.difference(B) == B.difference(A)
False

difference() returns the difference between two sets which is also a set. It doesn't modify the original sets.

A = {1, 2, 3, 4}
B = {2, 3, 9}

A - B
{1, 4}

B - A
{9}

A.difference(B)
{1, 4}
B.difference(A)
{9}

Symmetric difference: all elements that are in exactly one of the sets

The symmetric difference of two sets A and B is the set of elements that are in either A or B, but not in their intersection

a.symmetric_difference(b)
{5, 9, 11, 12}
a^b
{5, 9, 11, 12}

If we want to add a single element to an existing set, we can use the .add() operation. It adds the element to the set and returns 'None'.

s = set('abc')
s
{'c', 'a', 'b'}
s.add('d')
s
{'c', 'd', 'a', 'b'}
s.add('ef')
s
{'ef', 'b', 'c', 'd', 'a'}

Tuple:

A tuple is like a list that uses parentheses. The main difference between a tuple and a list is that a tuple cannot change once you’ve created it.

To Create tuple

>>>a = (0, 1, 1, 2, 3)

To convert a list to tuple:

>>> a = [0, 1, 1, 2, 3]


>>> print(a[3])
2
>>> tuple(a)
(0, 1, 1, 2, 3)
>>> a.index(3)
4
a.count(1)
2

Dictionary:

In Python, a map (also referred to as a dict, short for dictionary) is a collection of things, like lists and tuples. The difference between maps and lists or tuples is that each item in a map has a key and a corresponding value. We use colons to separate each key from its value, and each key and value is surrounded by single quotes. Notice, too, that the items in a map are enclosed in braces ({}), not parentheses or square brackets. Defining dictionary

>>> a = {}

Defining dictionary using dict fuction

>>> Names=dict()
>>> Names['First Name'] = 'jeeva'
>>> Names['Last Name'] = 'Kailasam'
>>> Names
{'Last Name': 'Kailasam', 'First Name': 'jeeva’}


>>> a['x'] = 'one'
>>> a['y'] = 'two'
>>> a
{'y': 'two', 'x': 'one'}
>>> 'x' in a
True
>>> a.get('x')
'one'
>>> a.keys()
['y', 'x']
>>> a.values()
['two', 'one']
>>> for k in sorted(a.keys()): print 'key:', k, '->', a[k]
...
key: x -> one
key: y -> two
>>> a.items() —> returns array of tuples
[('y', 'two'), ('x', 'one')]


>>> a={'first':'jeeva', 'last':'kailasam’}
>>> a.items()
[('last', 'kailasam'), ('first', 'jeeva’)]


>>> for key, value in a.items():
...  print(key, value)
...
first jeeva
last kailasam