Indexing list

list index

A list is a sequence of objects such as integers, stings, and other lists. The address of elements waiting for a list is called an index. The index is used to access and reference the item within a list. The index starts at 0. A list starts with [] and can be a string, float, or integer. listSet = ["name first", 10, 1, 2.5, "name last"]. Also, the index can start from -3 -2 -1.

List slicing | extend | append

Python
# list of numbers and strings. Modify the list by extending it with additional values
listSet = ["name first", 10, 1, 2.5, "name last"]
listSet.extend(["name middle", 3.5])
print(listSet) #output: ['name first', 10, 1, 2.5, 'name last', 'name middle', 3.5]
print("\n ") 
print(listSet[4:7]) #output: ['name last', 'name middle', 3.5] | 
# slicing the list from index 4 to 7
listSet.append("new user") 
Method Description
append() Adds a single item to the end of a list.
extend() Adds all the items of an iterable to the end of a list.

Change mutable list | del

Python
# Changing list elements
listOne = ["disco", 10, 1.5]
print('Before change:', listOne)
listOne[0] = 'hard rock'
print('After change:', listOne)
listOne.append(["name first", 10, 1, 2.5, "name last"])
print(listOne) 
# output: ['hard rock', 10, 1.5, ['name first', 10, 1, 2.5, 'name last']]
print("\n ")
del(listOne[0]) # delete the first element of the list
print(listOne) # output: [10, 1.5, ['name first', 10, 1, 2.5, 'name last']]

split()

split(','): This method is called on the string ‘A,B,C,D’. It splits the string into a list of substrings wherever it encounters a comma (,). So, the resulting list will be ['A', 'B', 'C', 'D'].

Python
# Split the string by comma

newlist = 'A,B,C,D'.split(',') 
print(newlist)
#output: ['A', 'B', 'C', 'D']

Close Bitnami banner
Bitnami