Accessing elements of a python List - python list element slicing

 #Accessing elements of a List:

we can access any item from a list using its index number

forward index stat with 0 end with n-1

negative indexing stat with -1

# accessing 2nd element of the list

Ex:

mylist = [10, 20, 'ram', 12.50, 'ravi']

print(mylist[1])  

output: 20

#Negative Indexing:

# accessing last element of the list

mylist = [10, 30, 'ram', 12.50, 'praveen']

print(mylist[-1])


python list element slicing:

syntax for list slicing.

listname[startindex : endindex : step]

Ex:

mylist = [10, 20, 'ram', 12.50, 'prasad', 25, 50]

print(mylist[1:4])

print(mylist[:3])     

print(mylist[::2])    

print(mylist[::-2])  

print(mylist[2:])   

Note :

# slice 1 index from before 4th index element

 # slice first three elements

# with a skip count 2

# reversing the list

 # Stating from 2nd item to last item

#Iterating a List : The objects in the list can be iterated over one by one, by using a for loop

Ex:

mylist = [15, 22, 'mohan', 7.50, 'rani']

for x in mylist:

    print(x)

output:

15

22

mohan

7.50

rani





    


No comments:

Post a Comment

Latest Post

How to Generate Barcode and QR code For Our Products

 మీ products కి barcode / QR code generate చేయాలంటే OPTION 1: ONLINE (No Coding – Quick) Best for small shops / beginners 👉Free websites: T...