LIST IN PYTHON
M3-R5.1 · Chapter 5: Sequence Data Types · 2 min read
1. Introduction to Lists
1. Definition:
A Python list is an ordered sequence of Heterogenous data type that are enclosed with Square Brackets and separated by commas.
Characteristics of a List
- Mutable: The elements within a list can be altered, added, or removed after the list is created.
- Ordered: The items have a defined sequence that does not change unless explicitly modified.
- Heterogeneous: A single list can contain elements of different data types, such as integers, floats, strings, tuples, or even other nested lists. It is highly useful for grouping mixed data.
- Zero-Indexed: List indices always start from 0 up to n-1 (where n is the number of elements).
Example
>>> list1 = [20, 5.5, 'hello']
>>> print(list1)
OUTPUT: [20, 5.5, 'hello']
2. List Indexing
Indexing allows you to access individual elements from the list.
- Positive Indexing: Starts from 0 for the very first element and goes up to n-1.
- Negative Indexing: Starts from -1 for the last element in the list and goes backwards down to -n.
Note: Attempting to access an index that does not exist will result in an Error.
Example :
>>> list1 = [20, 5.5, 'Hello']
>>> list1[0] # OUTPUT: 20
>>> list1[2] # OUTPUT: Hello
>>> list1[-1] # OUTPUT: Hello (last element)
>>> list1[-n] # OUTPUT: 20 (first element)
>>> list1[5] # OUTPUT: Error (index out of range)
3. List Operations
|
Operation |
Syntax |
Output |
|
Concatenation |
>>> [1,3,5,7,9] + [2,4,6,8,10] |
[1,3,5,7,9,2,4,6,8,10] |
|
Repetition |
>>> ['Hello'] * 5 |
['Hello','Hello','Hello','Hello','Hello'] |
|
Membership (True) |
>>> 'Amrit' in ['Varun','Ravindra','Amrit'] |
True |
|
Membership (False) |
>>> 'Nitin' in ['Varun','Ravindra','Amrit'] |
False |