Lists or Arrays in Python
List, in Python, is a collection of values/elements.
List can contain any Python (data)type.
Python lists are mutable/changeable.
These are like arrays in Shell/Perl scripting.
List can be used as Queue (FIFO) and Stack (LIFO). Default is Stack (LIFO).
Lists, in Python, are created by using square brackets, [ and ].
Elements are separated by commas.
List elements need not be unique. Element can appear in a list multiple times.
num_list = [2, 4, 6, 8]
char_list = ["C", "Java", "R"]
py_list = ["my", "list", a, b]
array_py = [88, "Python", False, (8,6)]
y = x + ["e", "f"]
Lists can be nested
family = [ ["Mom",35.3], ["Dad",34.4], ["Son",5.7], ["Daughter",2.5] ]
There are many ways to create lists.
empty_list = [ ]
>>> myList = [2] * 8 (>>> means interactive mode in Python)
list function can be used to create Python list.
empty_list = list()
>>> list(range(10))
>>> list(range(5,10))
>>> list(range(5,10,2))
list function can be used to convert Python Tuple to List.
input_list = list(input_tuple)
Reading input data and converting to list.
a = list(map(int, input().rstrip().split()))
list1 = sys.stdin.read().split(',')
Printing entire list
print list1
for val in list2: print(val)
Accessing some/required elements from list in Python
arr[i] # ith element, from left
area[6] # Positive index: count from the left, starting with 0
house[-1] # Negative index: count from right, starting with –1
arr[m:n] # Elements from m to n position. m ≤ i < n.
arr[m:n:increment] # Return a copy of the list with a subset of the original members. Start copying at the first index, and stop copying before second index.
x[3:7]
print(numbers[1:11:2])
print(numbers[::3])
>>> a[-5:-2]
nest_list[1][3]
x[2][:2]
>>> print(x[1][1][0], x[1][1][1])
fam[7] = 2.9 # Updating one element in a list
sea_creatures[-3] = 'blobfish'
list1[1:3] = [6]
area[0:2] = ["kkkk",8.666]
list3 = list(list1) # will copy values
list4 = list1[:] # will copy values
list5 = list1.copy() # will copy values
Using Python functions to operate lists.
len(arr) # to get length of list
max(nums) # to get maximum number of numerical list
min(nums) # to get minimum number of numerical list
arr.sort() # to sort elements in the list
sort(numbers)
print(sorted(pyList))
arr.reverse() # to sort elements in the list in reverse order
arr[len(arr)::-1] # to reverse Python list
numbers.sort(reverse = True)
print(sorted(pySet, reverse=True))
arr.append(66) # append takes a singleton as an argument
>>> a.append([1, 2, 3])
>>> a.append('foo')
arr.extend(["Python",True]) # extend takes a list as an argument, and apends to the list
arr.extend([10,11])
arr.insert(2, 88) # inserting new element, at a particular index
>>> lst.insert(3, "and")
arr.pop() # remove last element, argument defaults to -1
arr.pop(4) # remove 4th element
arr.remove(789) # removes element 789, only first occurrence
>>> colours.remove("green")
while el in list9: list9.remove(el)
arr.index('b') # finds leftmost element's index
>>> fruits.index('banana', 3)
>>> colours.index("green", 3, 4)
list6.rindex(xxx) # finds rightmost element's index
arr.count('b')
print(id(arr)) # internal python ID, refers memory location
ls = str1.split() # split using single/multiple whitespaces, converts a string to list
arr.split(:)
str = " ".join(list) # join converts a list to string
del(arr[3])
del(areas[-4:-2])
list.clear() # removes all elements
type(li) # list
type(list[1]) # int
type(list[1:1]) # list, because this is slice of strings
>>> l2 = list(l1)
>>> t[:]
for x in range(10): squares.append(x**2)
[x*2 for x in vec]
list1 == list5 # comparing two Python lists
list3 is list6 # comparing two Python lists
>>> [1, 2, 3, 4] == [4, 1, 3, 2]
False
>>> lst[:4] + lst[4:] == lst
True
zip(arr1, arr2)
zipped = list(zip(list_keys, list_values))
zippp = zip(list1, list2)
print(* zippp)
print(*zip(year, pop))
result1, result2 = zip(*zippp)
mutant_data = list(zip(mutants, aliases, powers))
for value1, value2, value3 in list(mutant_zip): print(value1, value2, value3)
en = enumerate(list1)
mutant_list = list(enumerate(mutants))
for ind, value in enumerate(list2, start=10): print(ind, value)
# Using Python list as queue (using collections package in Python)
# deque is a double-ended queue
from collections import deque
queue = deque(["Surya", "Aditya", "SUN"])
d = deque()
queue.append("Moon")
d.appendleft(2)
d.extend('7896')
d.extendleft('234')
d.count('1')
d.pop()
queue.popleft()
d.remove('2')
d.reverse()
d.rotate(3)
d.clear()
d.extend('1')
getattr(d, cmd)(*args)
print(*d)
List can contain any Python (data)type.
Python lists are mutable/changeable.
These are like arrays in Shell/Perl scripting.
List can be used as Queue (FIFO) and Stack (LIFO). Default is Stack (LIFO).
Lists, in Python, are created by using square brackets, [ and ].
Elements are separated by commas.
List elements need not be unique. Element can appear in a list multiple times.
num_list = [2, 4, 6, 8]
char_list = ["C", "Java", "R"]
py_list = ["my", "list", a, b]
array_py = [88, "Python", False, (8,6)]
y = x + ["e", "f"]
Lists can be nested
family = [ ["Mom",35.3], ["Dad",34.4], ["Son",5.7], ["Daughter",2.5] ]
There are many ways to create lists.
empty_list = [ ]
>>> myList = [2] * 8 (>>> means interactive mode in Python)
list function can be used to create Python list.
empty_list = list()
>>> list(range(10))
>>> list(range(5,10))
>>> list(range(5,10,2))
list function can be used to convert Python Tuple to List.
input_list = list(input_tuple)
Reading input data and converting to list.
a = list(map(int, input().rstrip().split()))
list1 = sys.stdin.read().split(',')
Printing entire list
print list1
for val in list2: print(val)
Accessing some/required elements from list in Python
arr[i] # ith element, from left
area[6] # Positive index: count from the left, starting with 0
house[-1] # Negative index: count from right, starting with –1
arr[m:n] # Elements from m to n position. m ≤ i < n.
arr[m:n:increment] # Return a copy of the list with a subset of the original members. Start copying at the first index, and stop copying before second index.
x[3:7]
print(numbers[1:11:2])
print(numbers[::3])
>>> a[-5:-2]
nest_list[1][3]
x[2][:2]
>>> print(x[1][1][0], x[1][1][1])
sea_creatures[-3] = 'blobfish'
list1[1:3] = [6]
area[0:2] = ["kkkk",8.666]
list2[3:] = [88, 99, 11]
list3 * 5
list1 + list4
list2 + [66] # concatenation produces new list
list3 * 5
list1 + list4
list2 + [66] # concatenation produces new list
list1 + list4
Copying one list to another
list2 = list1 # will copy references, id(list1) will be same id(list2)list3 = list(list1) # will copy values
list4 = list1[:] # will copy values
list5 = list1.copy() # will copy values
Using Python functions to operate lists.
len(arr) # to get length of list
max(nums) # to get maximum number of numerical list
min(nums) # to get minimum number of numerical list
arr.sort() # to sort elements in the list
sort(numbers)
print(sorted(pyList))
arr.reverse() # to sort elements in the list in reverse order
arr[len(arr)::-1] # to reverse Python list
numbers.sort(reverse = True)
print(sorted(pySet, reverse=True))
arr.append(66) # append takes a singleton as an argument
>>> a.append([1, 2, 3])
>>> a.append('foo')
arr.extend(["Python",True]) # extend takes a list as an argument, and apends to the list
arr.extend([10,11])
arr.insert(2, 88) # inserting new element, at a particular index
>>> lst.insert(3, "and")
arr.pop() # remove last element, argument defaults to -1
arr.pop(4) # remove 4th element
arr.remove(789) # removes element 789, only first occurrence
>>> colours.remove("green")
while el in list9: list9.remove(el)
arr.index('b') # finds leftmost element's index
>>> fruits.index('banana', 3)
>>> colours.index("green", 3, 4)
list6.rindex(xxx) # finds rightmost element's index
arr.count('b')
print(id(arr)) # internal python ID, refers memory location
ls = str1.split() # split using single/multiple whitespaces, converts a string to list
arr.split(:)
str = " ".join(list) # join converts a list to string
del(arr[3])
del(areas[-4:-2])
list.clear() # removes all elements
type(li) # list
type(list[1]) # int
type(list[1:1]) # list, because this is slice of strings
>>> l2 = list(l1)
>>> t[:]
for x in range(10): squares.append(x**2)
[x*2 for x in vec]
list1 == list5 # comparing two Python lists
list3 is list6 # comparing two Python lists
>>> [1, 2, 3, 4] == [4, 1, 3, 2]
False
>>> lst[:4] + lst[4:] == lst
True
zip(arr1, arr2)
zipped = list(zip(list_keys, list_values))
zippp = zip(list1, list2)
print(* zippp)
print(*zip(year, pop))
result1, result2 = zip(*zippp)
mutant_data = list(zip(mutants, aliases, powers))
for value1, value2, value3 in list(mutant_zip): print(value1, value2, value3)
en = enumerate(list1)
mutant_list = list(enumerate(mutants))
for ind, value in enumerate(list2, start=10): print(ind, value)
# Using Python list as queue (using collections package in Python)
# deque is a double-ended queue
from collections import deque
queue = deque(["Surya", "Aditya", "SUN"])
d = deque()
queue.append("Moon")
d.appendleft(2)
d.extend('7896')
d.extendleft('234')
d.count('1')
d.pop()
queue.popleft()
d.remove('2')
d.reverse()
d.rotate(3)
d.clear()
d.extend('1')
getattr(d, cmd)(*args)
print(*d)
Spot on with this write-up, I actually believe this amazing site needs a lot more attention.
ReplyDeleteI?ll probably be back again to read more, thanks for the information!
Good Python Blog with great articles on Basic Python data structures...
ReplyDelete