# Python Lists and List Manipulation [array pada python]

- Posted in Python by
``````# Define a list
z = [3, 7, 4, 2]

# Define a list
z = [3, 7, 4, 2]

# Access the first item of a list at index 0
print(z)
>> 3

# print last item in the list
print(z[-1])
2

# Define a list
z = [3, 7, 4, 2]

#Slices are good for getting a subset of values in your list. For the example code below, it will return a list with the items from index 0 up to and not including index 2.

print(z[0:2])
[3,7]

# everything up to but not including index 3
print(z[:3])
[3, 7, 4]

print(z[1:])
[7, 4, 2]
``````

method

``````# Define a list
z = [4, 1, 5, 4, 10, 4]

print(z.index(4))
0

random_list = [4, 1, 5, 4, 10, 4]
random_list.count(5)

``````

sort

``````z = [3, 7, 4, 2]
z.sort()
print(z)
>> [2,3,4,7]

z.sort(reverse = True)
print(z)
>>[7,4,3,2]
``````

Append

``````z = [7, 4, 3, 2]
z.append(3)
print(z)
>>[7, 4, 3, 2,3]
``````

remove

``````z = [7, 4, 3, 2, 3]
z.remove(2)
print(z)
>> [7, 4, 3, 3]
``````

extend

``````z = [7, 3, 3]
z.extend([4,5])
print(z)
>> [7, 3, 3,4,5]
# or
[7, 3, 3] + [4,5]
``````

insert

``````z = [7, 3, 3, 4, 5]
z.insert(4, [1, 2])
print(z)
>> [7, 3, 3, 4, [1, 2], 5]
``````

_https://hackernoon.com/python-basics-6-lists-and-list-manipulation-a56be62b1f95

Tags: