Lists are ordered, mutable (changeable) sequences of items. They can contain items of different data types.
Create lists using square brackets []
, separating items by commas:
You can access individual list elements by their index just like strings
Numerous methods available for List manipulation given use as one of more frequently seen in practice, these examples highlight main and common or helpful, practical ones of high utility in typical circumstances
Method | Description | Example | |
---|---|---|---|
append() |
Adds a new element at the end | my_list.append(6) |
|
insert() |
Inserts element at a specific index | my_list.insert(1,"SQL") |
|
extend() |
Adds all the elements of an iterable (list, tuple, string etc.) to the end | my_list.extend([7,8,9]) |
|
remove() |
Removes specified item. ValueError exception thrown if missing | my_list.remove("SQL") |
|
pop() |
Removes element at specified index | removed_element = my_list.pop(2) #removes at index 2 |
|
del() |
Keyword. Like prior remove/pop it can be given some positional numeric indice to remove and from thereby in terms of its effects although implemented quite differently | del my_list[0] # delete element at zeroth index |
|
clear() |
Deletes all from list making empty | my_list.clear() |
|
sort() |
sorts ascending if no argument is given otherwise uses specified | my_list = [3,1,4,1,5,9,2,6] sorts from lowest number upward like counting normally do, from small->large without need to change original, you sort rather than needing all other functions and loops and so on just to keep as originally organized for sake of not hardcoding initial element sequence rather than using indices later as could do given ordered unlike dict so remains correct regardless given sorting by method alone rather than original array contents themselves |
|
reverse() |
Reverses element order | my_list.reverse() |
|
copy() |
Creates/returns list copy | my_list2 = my_list.copy() # new_list variable you retain and do not lose initial for later even if same contents held |
|
count() |
counts num occurrences, specific val if that desired, you count everything inside list itself | cnt = my_list.count(1) # now cnt = 2 since we're seeing it twice within that initial list itself, 1 appearing two times within that whole unordered array variable itself so check against specific items when creating logic given how this counting function intended as designed and thereby functions when using Python code
| |
index() |
Gives position of specific value where if seen more than once in the data only returns its earliest matching numeric indice during a scan over values rather than multiple as would result otherwise |
pos= my_list.index(1) you locate positions only as result even if elements are repeated unlike prior example counting every appearance
|