[Coding test] 5. List

whitehousechef·2023년 11월 22일

pop

pop() pops the most righthand element like a stack

pop(0) pops the most lefthand element like a queue

but the time complexity is actually diff. pop() pops the last element in list so is o(1). but pop(0) pops the FIRST element so is o(n) cuz we need to shift the remaining elements to the left to fill the gap when we remove that element.

append(value or object like dict)

append() adds value at the most righthand element. there is no such thing as append(0) unlike pop(0) so if you wanna append at specific index, use insert(index,value). You can also append a dictionary to your list with append() like

my_list.append({"payer":payer, "point":point})

extend()

so unlike append that adds a single element, extend() iterates over the argument and adds each element individually to the list.

lst = [1, 2]
lst.extend([3, 4])
print(lst)  # [1, 2, 3, 4]

insert(index,value)

insert(index,value) inserts this value at a specific index. There is no append to add value to the most lefthand so in that case, use insert. This inserts value at that index so the elements after that value are shifted to the right.

# create a list of vowels
vowel = ['a', 'e', 'i', 'u']

# 'o' is inserted at index 3 (4th position)
vowel.insert(3, 'o')

print('List:', vowel)

# Output: List: ['a', 'e', 'i', 'o', 'u']

index(val)

.index(val) gives the index of the first occurrence of the val that you are looking for

remove(val)

.remove(val) removes the first matching element in the list with o(n) time

list of ints into integer value

Lets say we are given list like [2,0,2,4]. We want to convert that to 2024 integer value. First we have to map each integer value in that list to a string value via map(). This map function returns a list of strings now so we have to join them up with ‘’.join(string_lst). Finally, we convert this concatentated string to an integer via int().

Reason why we cant just do ''.join(int_list) is because join requires a list of strings, and we cannot give ints.

# Example list of integers
int_list = [1, 2, 3, 4]

# Convert the list to a string and then to an integer
int_value = int(''.join(map(str, int_list)))
print(int_value)

integer value to list of ints

What about the reverse? We first convert the integer to a string viastr() and iterate through each character and append them to a list. With list comprehension, it is like integer_lst=[int(digit) for digit in str(integer_value)]

# Example integer
int_value = 1234

# Convert the integer to a string, then each character back to an integer
int_list = [int(digit) for digit in str(int_value)]

# Print the result
print(int_list)

0개의 댓글