Skip to content

mmadil/python-tips

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 

Repository files navigation

Python tips

List of python tips

  1. Reverse a string or list
  2. Reverse by custom step
  3. List slice assignment
  4. Copy a list
  5. Create a list out of string
  6. Check file or directory exists
  7. Call an external command
  8. Ternary conditional operator
  9. for else

Reverse a string or list

my_list = ['a','b','c','d','e']
reverse_list = my_list[::-1]

my_string = "python"
print my_string[::-1]

Reverse by custom step

my_list = [1,2,3,4,5,6]
reverse_list = my_list[::-2]
# output : [6,4,2]

List slice assignment

  my_list = ['a','b','c','d','e']
  my_list[3:] = ['x','y','z']
  print my_list
  #output : ['a', 'b', 'c', 'x', 'y', 'z']

Copy a List

a = [1, 2, 3, 4]
''' Considered as one of the weirdest syntax to copy elements.'''
a_copy = a[:]

Create a list out of string

data = "abcd"
data_list2 = list(data)  # OutPut: data_list = ['a', 'b', 'c', 'd'] 

Check file or directory exists

os.path.isfile used only for files

import os.path
os.path.isfile(filename) # True if file exists
os.path.isfile(dirname) # False if directory exists

os.path.exists used for both files and directories

import os.path
os.path.exists(filename) # True if file exists
os.path.exists(dirname) #True if directory exists

Call an external command

from subprocess import call
call(['ls,'-l'])

Ternary conditional operator

print 'True' if True else 'False'

for else

my_string = ""
for i in my_string:
    print i
else :
    print 'String is empty'

About

List of python tips

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published