Sunday, October 25, 2020

Python Lists

Python has a builtin type name list. Lists values(elements/items) are enclosed within the square braces [] and separated by commas. Python lists are mutable and elements within the list can be replaced, removed. new elements can be inserted and appended. 


Python lists are heterogeneous, A list can contain a combination of different data types.

Here the list contains a integer, float and string

Accessing elements of List in Python:
Items/Elements of a list in python is accessed via index. List index starts from Zero, first element is accessed using zero, second element by 1 and so on. 
To access the elements from end the index starts from minus one (-1), last element in the list accessed using -1, second element from end is accessed using -2 and so on.To access fifth element from end use -5.

Accessing a List using Index Range:

Elements of a list can be accessed using the slicing operator . Range of indexes can be specified in a list where to start and end.
list[startIndex : endIndex : Step]

elements of the list are displayed from start of Index till end of Index. Index element 6 is excluded while accessing using the range.


In the above example list1 we have passed list1[2:10:2], here the elements from the position 2 till position 10 with a step of 2. step determines the position of next element to be evaluated after current position element. Here the element at index position 2 is 3 next element to be evaluated is determined using the step size. step size is 2 so the next element is 5, next element is 7 and so on.. 

Step size is equal to 3, so every third element is evaluated from start position of index till end position of Index.




 



No comments:

Post a Comment

Operations on Python Dictionaries