Creating A List: Create List Using List Comprehension
Creating A List: Create List Using List Comprehension
Creating A List: Create List Using List Comprehension
Creating a List
list2 = [1, 2, 3, 4, 5 ]
list() accepts either a sequence or tuple as the argument and converts into a Python list.
Syntax
Example
print(theList) #creates[0,1,2,3,4]
countries=["India","America","England","Germany"]
print(firstLetters) #Prints[‘I’,’A’,’E’,’G’]
Syntax
List[indexposition]
List(Startingindex,endingindex]
Example
list2 = [1, 2, 3, 4, 5, 6, 7 ];
Reverse Indexing
Python enables reverse (or negative) indexing for the sequence data type. So, for
Python list to index in the opposite order, you need to set the index using the minus (-)
sign. Indexing the list with “-1” will return the last element of the list, -2 the second last
and so on.
Example
my_list = ['p','r','o','b','e']
Syntax
theList[::-1]
The ‘-1’ after the second colon intends to increment the index every time by -1 and
directs to traverse in the backward direction.
Example
theList=[1,2,3,4,5,6,7,8]
print(theList[::-1])
Slicing a List
A slice is a subset of list elements. In the case of lists, a single slice will always be of
contiguous elements.
Syntax
list[start:end:step]
start (optional) - Starting integer where the slicing of the object starts. Default to None
if not provided.
stop - Integer until which the slicing takes place. The slicing stops at index stop -1 (last
element).
step (optional) - Integer value which determines the increment between each index
for slicing.
Example
theList=[1,2,3,4,5,6,7,8]
print(theList[2:5])
PY_5 List Page 3
print(theList[2:-1])
print(theList[:2])
print(theList[2:])
print(theList[2:5:2])
List Iteration
Python provides a traditional for-in loop for iterating the list. The for statement
makes it super easy to process the elements of a list one by one.
Print(element)
Example
list1=[1,2,3,4,5]
print(element)
Syntax
Print(index,element)
Example
list1=[1,2,3,4,5]
Syntax
Variable=iter(list)
Variable1=next(Variable)
Variable1=next(Variable) etc....
Example
list1=[1,2,3,4,5]
i=iter(list1)
element=next(i)
print(element)
element=next(i)
print(element)
Syntax
List[indexvalue]=newvalue
Example
theList[4]='C#'
print(theList)