Skip to content

python data structures

ghdrako edited this page Jul 18, 2023 · 13 revisions

List

x = [5, 3.0, 10, 200.2]
x = ['JupytherNB', 75, None, True, [34, False], 2, 75] 
x[4] = 52
len(x)
y = [9, 0, 4, 2]
print(x + y) # to concatenate two lists, + operator is used
print(y * 3) # to concatenate multiple copies of the same list, * operator is used
z = [y, x]   # to nest lists to create another list
#### Slicing
 use a colon to specify the start point (inclusive) and end point (noninclusive) of the sub-list

x[0:4] # the last element seen in the output is at index 3 x[:4] x[4:] x[-2:] x[0:4:2] # steps of 2 x[4::-2] # start from the element at index 4 and go backward to the beginning with steps of 2

#### Modifing

x.append(-23) x.remove(75) y.sort() # to sort the element of y x.insert(2, 10) # insert(pos, elmnt) method inserts the specified elmntat the specified position (pos) and shift the rest to the right print(x.pop(3)) # pop(pos) method removes (and returns) the element at the specified position (pos) del x[1] # delete an element from a list by its index x.pop() # by default the position is -1, which means that it removes the last element

Coping

>>>list1 = ['A+', 'A', 'B', 'C+']
>>>list2 = list1
>>>list2.append('D')
>>>print(list2)
>>>print(list1)
['A+', 'A', 'B', 'C+', 'D']
['A+', 'A', 'B', 'C+', 'D']

Deep copy

Test

Clone this wiki locally