Course Eleven - Use Lists in Python language

Use Lists in Python language

By ienex



Lists are one of the most versatile sequence data types in Python. Each element in a list has a position or index, starting from 0. Python supports several sequence types, but lists and tuples are the most commonly used.


Creating Lists

A list is created by placing comma-separated values inside square brackets []. List items do not have to be of the same type:

list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5]
list3 = ["a", "b", "c", "d"]

Accessing List Elements

Use square brackets to access elements by their index or a slice of the list:

list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7]

print("list1[0]:", list1[0])
print("list2[1:5]:", list2[1:5])

Output:

list1[0]: physics
list2[1:5]: [2, 3, 4, 5]

Updating List Elements

You can update a single element or a slice of elements. To add new items, the append() method can be used:

list1 = ['physics', 'chemistry', 1997, 2000]

print("Value at index 2:", list1[2])
list1[2] = 2001
print("Updated value at index 2:", list1[2])

Output:

Value at index 2: 1997
Updated value at index 2: 2001

Deleting List Elements

Use the del statement if you know the index, or remove() to delete by value:

list1 = ['physics', 'chemistry', 1997, 2000]
print(list1)

del list1[2]
print("After deleting value at index 2:", list1)

Output:

['physics', 'chemistry', 1997, 2000]
After deleting value at index 2: ['physics', 'chemistry', 2000]

Basic List Operations

Lists support operations like length, concatenation, repetition, membership tests, and iteration:

Expression Result Description
len([1,2,3]) 3 Length
[1,2,3] + [4,5,6] [1,2,3,4,5,6] Concatenation
['Hi!']*4 ['Hi!','Hi!','Hi!','Hi!'] Repetition
3 in [1,2,3] True Membership
for x in [1,2,3]: print(x) 1 2 3 Iteration

Indexing and Slicing

Lists work like strings in terms of indexing and slicing:

L = ['spam', 'Spam', 'SPAM!']
print(L[2])   # 'SPAM!'
print(L[-2])  # 'Spam'
print(L[1:])  # ['Spam', 'SPAM!']

Built-in Functions for Lists

Function Description
cmp(list1, list2) Compare two lists
len(list) Length of the list
max(list) Maximum element
min(list) Minimum element
list(seq) Convert a sequence to a list

Common List Methods

Method Description
list.append(obj) Add an element to the end
list.count(obj) Count occurrences of an element
list.extend(seq) Add elements from another sequence
list.index(obj) Return index of first occurrence
list.insert(index, obj) Insert element at a specific position
list.pop([index]) Remove and return element at index (default last)
list.remove(obj) Remove first occurrence of value
list.reverse() Reverse the list
list.sort([func]) Sort elements, optional custom comparison


Comments

Popular posts from this blog

Why You Should Learn JavaScript and Python in 2025

Why you Should Learn JavaScript and Python ?

Course Six - Operators in Python