List is an ordered collection of values.Unlike other languages list elements in Python can be of different types.
Create a list in Python
- To create a list declare list variable just like a normal variable.
- Assign list of comma separated values inside square brackets
num_list=[1,2,3,4,5]
above will create list of numbers
to create list of strings use:
str_list=['a','b','c','random string']
Accessing list elements
As the elements in list are ordered so you can access them by index .to access the element of the list use index inside square brackets:
str_list[0] will return ‘a’
str_list[3] will return ‘random string’
Using negative index
to acess the elements relative to the last element use negative values So second last element can be accessed as:
str_list[-2]
and last element will be
str_list[-1]
adding new items to a list
Slicing
we can retrieve a part of the last from the original list.This is called slicing.To use slicing you specify start index followed by colon(:) and end index.For example to retrieve the first two elements from the above list in a new list use:
str_list[0:2]
this will return ‘a’,’b’ in a new list
Add elements to list
There are different ways of adding elements to list:
-
using the plus (+) operator
str_list=str_list+['d','e']
-
using the append() method
str_list.append('f')
-
using the insert() method
str_list.insert(1,'0')
the item is inserted at the specified index.
Finding number of Items in a List
len(object) method is useful for finding the length of list.You can use this inbuilt method with other sequences such as tuples and dictionary as well.For example,you can use it as:
numbers=['1','2','3'] len(numbers)
Leave a Reply