Python List – A quick reference


  1. List is a sequence of values, In string, every value is character, in list – mixed types.
  2. Mutable
  3. Aabhar : http://do1.dr-chuck.com/pythonlearn/EN_us/pythonlearn.pdf
myList = [1, "Two", [11.0,17.0], list(), [] ]

# ======== Print values in either ways
for x in myList:
    print(x)

""" # RESULT -> 
1
Two
[11.0, 17.0]
[]
[]
"""
    
for i in range(len(myList)):
    print("At index ", i , " => ", myList[i])
""" # RESULT -> 
At index  0  =>  1
At index  1  =>  Two
At index  2  =>  [11.0, 17.0]
At index  3  =>  []
At index  4  =>  []
"""

# ======== Slice Operations
print(myList[0:3])  #index o to 2
# RESULT ->  [1, 'Two', [11.0, 17.0]]

print([1,2,3,4,5][:3]) #Upto Index 2
# RESULT ->  [1, 2, 3]

print(["One", "Two", "Three", "Four"][2:]) # From Index 2 till end
# RESULT ->  ['Three', 'Four']

# ======== Concat & Repeatation
l1 = [1,2,3]
l2 = [4,5,6]
print(l1 + l2)
print (l1 * 4)
# RESULT ->  [1, 2, 3, 4, 5, 6]
# RESULT ->  [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]


#  ======== Methods
m1 = [8,7,100]
m1.extend(m1) #Concat with another list to it
print(m1)
# RESULT ->  [8, 7, 100, 8, 7, 100]

m2 = [2,3]
m2.append( [222,333] ) # You can pass just one element
print(m2)
# RESULT -> [2, 3, [222, 333]]


t = ['d', 'c', 'e', 'b', 'a']
t.sort()  # Dont assign as returns None
print(t)
# RESULT -> ['a', 'b', 'c', 'd', 'e']

# ======== Deleting a value
#1. pop() -> deletes the last value until you provide the index
m1 = [1,2,3,4]
print(m1.pop(), " --- ", m1)
print(m1.pop(0), "---", m1)
# RESULT -> 4  ---  [1, 2, 3]
# RESULT -> 1 --- [2, 3]


#2. del will simply delete without being remembered
m2 = [11,22,33,44,55]
#delValue = del m2[2]  # This is invalid, you cant assign
del m2[2:4]  #The return value from del is None.
print(x, " ----", m2)
# RESULT -> []  ---- [11, 22, 55]


# del the desired element without knowing the index
m3 = [1,2,2,3,4]
m3.remove(2)  # Only 1st occurrence
print(m3)
# RESULT -> [1, 2, 3, 4]

# ======== Built-in methods
y = [0,1,2,99]
print(min(y), max(y), len(y), sum(y))
# RESULT ->   0 99 4 102

# Convert string to list
x = 'Python World'
y = list(x)
print(y)
# RESULT ->   ['P', 'y', 't', 'h', 'o', 'n', ' ', 'W', 'o', 'r', 'l', 'd']


z = x.split(" ")
print(type(z), " ---", z)
# RESULT ->   <class 'list'>  --- ['Python', 'World']
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s