List Python

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

#CASE1:

#Create Python Lists of Integers

my_list = [1,2,3]

#Create Python List of different types (integer, float, string, etc)

#empty list

my_list = [ ]

#list with mixed data types

my_list = [1,”Hello”,3.4]

#Nested List

my_list = [“CS”,[8,4,6], [‘a]] #Nested lists are accessed using nested indexing

#CASE 2:

#Access List Elements

my_list = [‘p’ , ’y’ , ’t’ , ’h’ , ’o’ , ’n’]

print(my_list[0]) #p

print(my_list[2]) #t

# Nested List
n_list = ["Happy", [2, 0, 1, 5]]

# Nested indexing
print(n_list[0][1]) #a

print(n_list[1][3]) #5

#CASE 3:

# Negative indexing in lists


my_list = ['p','y','t','h','o',’n’]

# last item
print(my_list[-1]) #n
# fifth last item
print(my_list[-5]) #y

#CASE 4:

#Add/Change List Elements

odd = [2, 4, 6, 8]

# change the 1st item


odd[0] = 1
print(odd) #[1,4,6,8]

# change 2nd to 4th items


odd[1:4] = [3, 5, 7]

print(odd) #[1,3,5,7]

#CASE 5

# Appending and Extending lists in Python


odd = [1, 3, 5]
odd.append(7)
print(odd) #[1,3,5,7]
odd.extend([9, 11, 13])
print(odd) #[1,3,5,7,9,11,13]

#CASE 6

# Deleting list items


my_list = ['p', 'y', 't', 'h', 'o', 'n']

# delete one item


del my_list[2]

print(my_list) #pyhon

# delete multiple items


del my_list[1:4]
print(my_list) #pn

# delete the entire list


del my_list

You might also like