Lists - mrprov12/DSPrep GitHub Wiki

Lists

x = list(y), x = [] ->> defining a list
list[x] ->> call x index from list
indicies = range(len(list))
list(fliter9func, iterable)): returns True elements into array
accessing multpile elements: list[0:2] = list[incl:excl]

List Basics

A list is a collection of arbitrary objects, often called an array in other programming languages. The contents of a list can be thought of as ordered, in that a list guarantees that its contents are numerically indexed. The items, or elements of a list can be accessed by the numeric index. In Python, a list is mutable in the sense that its contents can be rearranged, replaced, or deleted. A list can be nested to arbitrary depth. The list datatype is the primary construct on which you will perform iteration, or going item-by-item across a data structure.

LISTS ARE MUTABLE

creating a list:

some_list = [] some_list = [x,y,z] some_list = list() some_list = list(some_other_collection)

calling an elem from a list:

my_list[index_of_elem]

note: -1 as index will call last elem in list

indexing begins at 0

changing elem in list at index:

<list_name>[<index_of_element_to_change>] = <new_value_for_index>

concatenating lists:

can concatenate lists with '+' operator

  ``` python
  first_list = ['This', 'is', 'list', '1']
  second_list = ['add', 'me', 'to', 'list', '1']

  concatenated_list = first_list + second_list

  # This will print ['This', 'is', 'list', '1', 'add', 'me', 'to', 'list', '1']
  print(concatenated_list)
  ```

list memembership:

elem in lst checks if in list, and returns bool True if so elem not in lst checks if in list, returns bool True if not

list slicing:

sublst[start:stop] sublst[negative_start: negative_stop]

...where: start is an index at which our "slice" will begin stop is also an index before which our "slice" will end Thus, start will be included in the sublist, but stop will not be OR: negative_start is a negative index at which our "slice" will begin negative_stop is also a negative index after which our "slice" will end Thus, negative_start will be included in the sublist, but negative_stop will not be

nested lists:

####creating:

    nested_list_example_2 = [list(), list(), list()]
  # OR
    nested_list_example_3 = [[], [], []]

accessing:

```python
nested_list = [['a', 'b', 'c'], [1, 2, 3]]

# Use indexing to access the second element in the first nested list<br>
element_within_nested_list = nested_list[0][1]<br>
print(element_within_nested_list)


nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for i in nums:
  for j in i:
    print(j)
    ```

####slicing:

  start = 10
  end = 21

  num_list = list(range(start, end))
  overall_list = [['a', 'b', 'c'], num_list, [6, 7, 8]]

  # Assign and print the elements in indeces 2, 3, 4, 5, 6 from num_list
  sublist = overall_list[1][2:7]
  print(sublist)

unpacking a list:

some_list = ['pig', 'boar', 'elephant'] a, b, c = some_list

#a = 'pig, b = 'boar', c='elephant'

functions and methods

range([start], stop[, step]):

start: Starting number of the sequence. stop: Generate numbers up to, but not including this number. step: Difference between each number in the sequence.

Note that:

All parameters must be integers. All parameters can be positive or negative. range() (and Python in general) is 0-index based, meaning list indexes start at 0, not 1. eg. The syntax to access the first element of a list is mylist[0]. Therefore the last integer generated by range() is up to, but not including, stop. For example range(0, 5) generates integers from 0 up to, but not including, 5.

.copy()

equivalent to: lst[:]

.index(elem)

returns the index of first instance of element in list

.append(elem)

adds element to end of list

.extend(lst)

extends current list by argument list

.remove(elem)

removes first instance of element

del

del lst[i]
deleted element at specified index

len(lst)

returns the length of the argument list

sum(lst)

returns numeric sum of all elements in list

sorted(lst)

returns a sorted version of argument list
MUST BE SAVED TO NEW VAR TO REMAIN PERMENANT, does not make any permenant changes to original list

reversed(lst)

returns reversed version of argument list
MUST BE SAVED TO NEW VAR TO REMAIN PERMENANT, does not make any permenant changes to original list Also, must be cast to list with [] as returns reversed obj rather than list

max(lst)

returns max num in list

min(lst)

returns min num in list

any(lst)

returns bool True if any elem in list are truthy

all(lst)

returns bool True only if ALL elem in list are truthy

enumerate

for i, elem in enumerate(list): iterates through both i and elem in list

zip

for a,b,c in zip(list_1, list_2, range(len(list_3))): #iterates through parallel lists at same time

.append(item)

item added to end of th elist
can be any datatype
returns None

.clear()

removes all items from the list

.copy()

copies old list to new list, changes to new list won't effect old list (unlike =)
also can use slicing (new_list = list[:])

.count(element)

returns # of times element is in list
can be used with nested lists and tuples

.extend(iterable)

adds all the elements of an iterable (list, tuple, string, etc) to the end of the list
Modifies original list, does not return value
also can append all elements to list using: + +=
list slicing:
a = [1,2]; b = [3,4]
a[len(a):] = b
a = [1, 2, 3, 4]
merges rather than append

.index(element, start, end)

returns the index of the specified element in the list
element: element to be searched
start (op): start from this index
end (op): search up to this index
returns index of given element OR ValueEror if not found
*only returns 1st occurane of element

.insert(i, elem)

inserts element into list @ ith index
all elements after elem shifted to right
returns None, updates current list
*can insert Tuples as elements

.pop(index)

removes and returns an element at a given index from a list
if index not passed, returns for (-1)

.remove(element)

removes the first matching element (which is passed as an arg) from list
throws error if element DNE
returns None, or error
if need to delete elements based on index, use .pop()

.reverse()

reverses the elements of the list
returns None
can also do with slicing operator: reversed_list = list [::-1]
accessing items in reversed order: for x in reversed(list):

.sort(key=..., reverse=...)

key (op): func that serves as key for he sort comparison
reverse (op): if True, sorted list is sorted in descending order
changes original list
no return
to return sorted list (with original unchanged) use sorted()
ie. list.sort(key = len, reverse = true/false)
OR sorted(list, key=len)

⚠️ **GitHub.com Fallback** ⚠️