How to create a list and its operations???

Python collections

    Collection is a set of elements stored in a sequence. In python, there are 4 types of collections.

They are

  • List
  • Tuple
  • Set
  • Dictionary

In the above collections, list has variety of operations to do.

Lists

 List is a collection in python. It can store any type of data. It has variety of operations to perform like creating, displaying, access, add, delete, search and so on.

1.Creating a list

 This is the way of creating a new list in python. Colorlist is the list name. Red,Green,Yellow are the values. 

colorlist=[“Red”,”Green”,”Yellow”]

print(colorlist)

 When you execute this code, you get the following output.

['Red', 'Green' ,'Yellow']

2.Access the list items

  After creating the list, you can access the items. Here,it displays the data in first position. list is always starts from index 0.

colorlist=[“Red”,”Green”,”Yellow”]

print(colorlist[1])

 The output is:

  Green

3.Change the value:

If want to change a particular value in the list, you can assign it with another value. Here, is the code...

colorlist=[“Red”,”Green”,”Yellow”]

colorlist[2]=”Blue”

print(colorlist)

while you execute this code, you can get the following output.

['Red', 'Green', 'Blue']

4.Search an item in the list:

 If you want to find an item in the list, use the below code.

colorlist=[“Red”, “Green”, ”Yellow”]

if “Red” in colorlist:

   print(“ Yes, ‘Red’ is in the colorslist”)

 output is:

 Yes, ‘Red’ is in the colorslist

5.Finding length of the list

To find the length of the list,  use the code given.

colorlist=[“Red”, “Green”, ”Yellow”]

print(len(colorlist))

The output is given below.

3

These are the basic operations performed in the list.


No comments:

Post a Comment