Lists in Python

x = [1,2,3,4,'five']
#This is how a list looks like
# They can hold different data such as numbers strings and floats
# Values in the lists are seperated by the commas

List built in Functions

x = ['one,'two','three']
# This will printout the number of items present in the list
x = range(1,4)
# this print [1,2,3]

Different way of accessing the data in the lists

x = ['john','jason','tony']
print(x[0]) # This will john
print(x[0]) # This will jason
print(x[0]) # This will tony
x = [1,2,3]
1 in x
# this will print true
4 in x
#this will print false because 4 is not in the list

We can also iterate throught the list using loops

list = ['blue','yellow','green','orange','black']
for color in list:
# Using while loop
i = 0
while i < len(list):
    i += 1 
#len() function tells us how many items are there in the list        

Note: len() can also be used on the strings

List Methods

These methods are used to add items to the list

x = [1,2,3,4,5]
# This print [1,2,3,4,5,[6,7,8,9]]
#Lets use the extend method on this
#This will print out [1,2,3,4,5,6,7,8,9]
x = [1,2,3,4]

Methods that are used to delete items from the list

x = [1,2,3,4]
x.pop()# this will remove the last item by default
#this will remove the item at index [1]
x = [1,2,3,4]
#this will remove 1 in the list

Other List Methods

x = [1,'hi',2,3,4]
#this will print the index of the 1 which is 0
x = [1,1,2,3,4,5]
#This will check if the element is being repeated 
#This method will reverse the list
# the output is going to be like [4,3,2,'hi',1]
x = [3,2,4,1]
#This will sort out the list
# The output will be [1,2,3,4]
x = ['1','2','3']
' '.join(x)
#Output 1 2 3
#this will add the space

Lists Slicing

#lists slicing
# some_list[start:end:step]
# start is to where to start
# end is to where to end
# Step is the intervals

x = [1,2,3,4,5,6]
# This will print [1,2] 3 is not included becuase its exclusive
#This will print [2,4,6]
# Easy way to reverse a list x[::-1]
#Swapping Lists
y = ['John','Jason']
y[0],y[1] = y[1],y[0]

List Comprehension

nums = [1,2,3,4,5,6,7,8]
y = [x*x for x in nums]
# This will print 
# We can also use a loop
new_list =[]
for x in nums:
    sqaure = x*x
#This piece of code is doing the same thing but the only difference is that the other method is much easier
# This can also be used to convert into strings
[str(x) for x in nums]
# This will print everything in the list that was present in int.
# We can also use the conditonal statements in lists
[x for x in num if x%2==0]
#This will print all the even numbers in the lists