2.strings lists
Strings
Collection of Characters
Popular string methods
Methods | Description |
---|---|
len(string) | to know the length of the string. |
string[index] | to get specific character from the string. |
string[start:end] | to get the group of characters from start index position to end index position of string. |
string[start:end:step] | to get the group of characters from start index position to end index position of string based on the step size. By default step size will be 1 |
string[::-1] | reverses the string. |
string.upper() | coverts the string characters to upper case. |
string.lower() | converts the string characters to lower case. |
string.split() | to split the string, by default split function splits the string based on white space. |
string.split(character) | to split the string based on a specific character |
Lists
Collection of objects
mylist = [1, 2.3, 'Hi']
nestedlist = [1, 2.3, 'Hi', [1, 2]]
List Slicing
- can get the elements of a list using index.
- Index starts with 0.
- to select first element of a list
mylist[0]
-
to get the elements from the end of the list, like to get last element,
mylist[-1]
ormylist[2]
we will use negative number to start the cursor from end. -
To select multiple elements from list.
mylist[start, end]
The start index will be included, while the end index is not.
mylist[start:end:step]
step indicates the step size between the elements
Example
mylist = [1, 2, 3, 4, 5, 6, 7]
print(mylist[3:5])
result:
[4,5]
List Manipulation
- Add elements to the list.
list + new element
- Remove element from the list.
del(list[i])
Example
x = [a, b, c]
# address allocating
y = x
y[1] = z
print(x)
result:
[a,b,c]
x = [a, b, c]
y = list(x)
y = x[:]
y[1] = z
print(x)
result:
[z,b,c]
Popular List Methods
Methods | Description |
---|---|
len(list) | to know the length of the list |
list.append(el) | to append the element to the list |
list.pop(index) | to pop out the element from the list |
list.sort() | to sort the elements of the list |
list.reverse() | to reverse the elements of the list |
list.max() | to get the maximum value of the list |
list.min() | to get the minimum value of the list |