Powered by Ajaxy
Digg StumbleUpon LinkedIn YouTube Flickr Facebook Twitter RSS Reset

Python: Replace slice items

li = ['java', 'cpp', 2012, "1234", "python"]
print li                  #['java', 'cpp', 2012, '1234', 'python']
li[2:-1] = ["C#", "PHP"]
print li

Python: comparing lists

a = [1, 2, 3, 4]
# compare two lists
result= a < [1, 2, 3, 5]
print result
result= a < [int(1), int(2), int(3), int(5)]
print result;
# Compare lis

Python-List: How to use in and not in function

myList = [1, "two", 3, 4.0]
print myList # [1, 'two', 3, 4.0]
print 1 in myList # True
print 3 in myList[:1]# False
print 'two' not in myList#False

Python: Reversing a List

a = ['spam', 'eggs', 100, 1234]
a.reverse();
print a

Python: create a new temporary file

import tempfile, os fd, 
path = tempfile.mkstemp(suffix='.txt', text=True)
try:
    os.close(fd)
    use_filepath(path)
finally:
    os.unlink(path

Python: How to find Prime numbers using a list

# list of non-prime numbers
nbr = [j for i in range(2, 8) for j in range(i*2, 100, i)]
# get the "inverse" of the list, which are prime numbers
nbr

Python: Finding the Length of a list

# list size
print len(()) # 0
print len([]) # 0
# define a list with values
baaa= [1, 2, 3,4]
print len(baaa) # results: 4
fooo=[[0,baaa,"sakoba"],

Python: Slicing a List

# Define a list
myList=[1, 2, 3, 4, 5]
print "My List: ",myList #My List:  [1, 2, 3, 4, 5]
# returns the segment starting with the index 1 and up t

Python: sort the items of a list

import math
myList=[2.0, -9.5, 78, -0.14, 13, 45, -51, round(math.pi, 0)]
print "Unsorted list: ",myList
myList.sort() # sort
print "Sorted list: "

Python: Append item to a list

# define a liste
maListe = ['January', 'february', 'March', 'April', 'May']
#print
print maListe
elem = raw_input("Enter the month's name after May

Python: Processing a list

list1 = ["One", "Two", "Three"]
list2 = ["Five", "Six"]
print list1
#Append item
list1.append("Four")
print list1
#Insert item at index
list1.inser

Python: Indexing a List as an array

#Define a list of 5 items
myList=["Zero", 1, 2,'three', 4]
print myList[0] # Zero
#retrieve an item from the end 
print myList[-2]

Python: How to concatenate two lists

a = [1, 2, 3]
print a # [1, 2, 3]
# add the items in the sequence 
a.extend([8/2])
print a #[1, 2, 3, 4]
# concatenate with list
a.extend([[ 5, 7]]

Python: create a list of characters from a String

word = "Python"
list = []
for ch in word:
    list.append(ch)
print list # ['P', 'y', 't', 'h', 'o', 'n']

Python: Replacing List Items

myList=[1, 2, 3, 4, 5]
print myList
# Replace the third item of the list
myList[2]='trois'
print myList
# Replace the second item
myList[1]= -myLis