list¶
- lists are a fundamental data structure used to store collections of items in an ordered and changeable way.
- You can create lists using square brackets
[]
and separate items with commas. - Lists can contain items of different data types (strings, integers, floats, booleans, even other lists) within the same list.
- Elements in a list are indexed starting from 0. The first element has index 0, the second element has index 1, and so on.
- You can access elements using their index within square brackets.
- Negative indexing allows you to access elements from the end of the list. -1 refers to the last element, -2 to the second-last, and so on.
- You can extract a portion of a list using slicing with square brackets and colons (
:
) - The syntax is
[start:end:step]
start
(optional): Index of the first element to include (inclusive). Defaults to 0.end
(optional): Index of the element to exclude (exclusive). Defaults to the list length.step
(optional): Number of steps to take between elements. Defaults to 1 (iterates through all elements).
- Lists are mutable, meaning you can change their contents after creation.
- You can assign a new value to an element using its index.
- methods to add or remove elements from a list
append(element)
: Add an element to the end of the list.insert(index, element)
: Insert an element at a specific index.remove(element)
: Remove the first occurrence of an element (error if not found).pop(index)
: Remove and return the element at a specific index (or the last element by default).
- Common List Operations
len(list)
: Returns the length (number of items) in the list.in
andnot in
: Check if an element is present in the list.list.extend(iterable)
: Extends the list by appending all elements from another iterable (like another list).
- Key Points
- Lists are versatile and can store various data types.
- Indexing provides access to individual elements.
- Slicing allows you to extract sublists.
- Lists are mutable, enabling modification of their contents.
- Various methods offer functionalities for adding, removing, and manipulating list elements.
In [ ]:
Copied!
# create list
fruits = ["🍎", "🍌", "🍒"]
print(fruits) # ['🍎', '🍌', '🍒']
numbers = [1, 2, 3, 4.5]
print(numbers) # [1, 2, 3, 4.5]
mixed_list = ["hello", 10, True]
print(mixed_list) # ['hello', 10, True]
# create list
fruits = ["🍎", "🍌", "🍒"]
print(fruits) # ['🍎', '🍌', '🍒']
numbers = [1, 2, 3, 4.5]
print(numbers) # [1, 2, 3, 4.5]
mixed_list = ["hello", 10, True]
print(mixed_list) # ['hello', 10, True]
In [ ]:
Copied!
# get items from list
first_fruit = fruits[0] # first_fruit will be "🍎"
print(first_fruit) # 🍎
last_number = numbers[-1] # -1 refers to the last element, last_number will be 4.5
print(last_number) # 4.5
# appending items to list
fruits.append("🥭") # ['🍎', '🍌', '🍒', '🥭']
print(fruits)
# get items from list
first_fruit = fruits[0] # first_fruit will be "🍎"
print(first_fruit) # 🍎
last_number = numbers[-1] # -1 refers to the last element, last_number will be 4.5
print(last_number) # 4.5
# appending items to list
fruits.append("🥭") # ['🍎', '🍌', '🍒', '🥭']
print(fruits)
In [ ]:
Copied!
# slicing list
# s[i:j] 👈 slice of s from i to j
print(fruits[1:3]) # ['🍌', '🍒']
# s[i:j:k] 👈 slice of s from i to j with step k
print(fruits[1:4:2]) # ['🍌', '🍒']
print(fruits[::3]) # ['🍎', '🥭'] (elements at index 0 and 3, takes every 3rd item starting from item 0)
print(fruits[::-3]) # ['🥭', '🍎'] (elements at index -1 and -3, takes every 3rd item starting from item -1)
# traversing within list
for fruit in fruits:
print(fruit)
# slicing list
# s[i:j] 👈 slice of s from i to j
print(fruits[1:3]) # ['🍌', '🍒']
# s[i:j:k] 👈 slice of s from i to j with step k
print(fruits[1:4:2]) # ['🍌', '🍒']
print(fruits[::3]) # ['🍎', '🥭'] (elements at index 0 and 3, takes every 3rd item starting from item 0)
print(fruits[::-3]) # ['🥭', '🍎'] (elements at index -1 and -3, takes every 3rd item starting from item -1)
# traversing within list
for fruit in fruits:
print(fruit)
In [ ]:
Copied!
# copying list
fruits_copy = fruits.copy()
print(fruits_copy) # ['🍎', '🍌', '🍒', '🥭']
# replacing item in list
fruits_copy[1] = "🥭" # Replace "🍌" with "🥭"
print(fruits_copy) # ['🍎', '🥭', '🍒', '🥭']
# copying list
fruits_copy = fruits.copy()
print(fruits_copy) # ['🍎', '🍌', '🍒', '🥭']
# replacing item in list
fruits_copy[1] = "🥭" # Replace "🍌" with "🥭"
print(fruits_copy) # ['🍎', '🥭', '🍒', '🥭']
In [ ]:
Copied!
# list comprehension.
squares = [i**2 for i in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# list comprehension.
squares = [i**2 for i in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [ ]:
Copied!
# x in s 👈 True if an item of s is equal to x, else False
print("🥭" in fruits) # True
# x not in s 👈 False if an item of s is equal to x, else True
print("🥭" not in fruits) # False
# s + t 👈 the concatenation of s and t
print(fruits + squares) # ['🍎', '🥭', '🍒', '🥭', 0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# s * n or n * s 👈 equivalent to adding s to itself n times
print(fruits * 2) # ['🍎', '🥭', '🍒', '🥭', '🍎', '🥭', '🍒', '🥭']
# x in s 👈 True if an item of s is equal to x, else False
print("🥭" in fruits) # True
# x not in s 👈 False if an item of s is equal to x, else True
print("🥭" not in fruits) # False
# s + t 👈 the concatenation of s and t
print(fruits + squares) # ['🍎', '🥭', '🍒', '🥭', 0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# s * n or n * s 👈 equivalent to adding s to itself n times
print(fruits * 2) # ['🍎', '🥭', '🍒', '🥭', '🍎', '🥭', '🍒', '🥭']
In [ ]:
Copied!
# len(s) 👈 length of s
print(len(squares))
# min(s) 👈 smallest item of s
print(min(squares))
# max(s) 👈 largest item of s
print(max(squares))
# s.index(x[, i[, j]]) 👈 index of the first occurrence of x in s (at or after index i and before index j)
print(fruits_copy.index('🥭', 2, 4))
# s.count(x) 👈 total number of occurrences of x in s
print(fruits_copy.count('🥭'))
# s.append(x) 👈 appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
fruits_copy.append("🍊")
print(fruits_copy) # ['🍒', '🍌', '🍎', '🍒', '🍌', '🍎', '🥑', '🍊']
# s.clear() 👈 removes all items from s (same as del s[:])
fruits_copy.clear()
print(fruits_copy) # []
# s.extend(t) or s += t 👈 extends s with the contents of t (for the most part the same as s[len(s):len(s)] = t)
fruits_copy.extend(fruits)
print(fruits_copy) # ['🍎', '🍌', '🍒', '🥭']
# s *= n 👈 updates s with its contents repeated n times
fruits_copy *= 2
print(fruits_copy) # ['🍎', '🍌', '🍒', '🥭', '🍎', '🍌', '🍒', '🥭']
# s.insert(i, x) 👈 inserts x into s at the index given by i (same as s[i:i] = [x])
fruits_copy.insert(1, "🥑")
print(fruits_copy) # ['🍎', '🥑', '🍌', '🍒', '🥭', '🍎', '🍌', '🍒', '🥭']
# s.pop() or s.pop(i) 👈 retrieves the item at i and also removes it from s
print(fruits_copy.pop()) # 🥭
# s.remove(x) 👈 remove the first item from s where s[i] is equal to x
fruits_copy.remove("🥭")
print(fruits_copy) # ['🍎', '🥑', '🍌', '🍒', '🍎', '🍌', '🍒']
# s.reverse() 👈 reverses the items of s in place
fruits_copy.reverse()
print(fruits_copy) # ['🍒', '🍌', '🍎', '🍒', '🍌', '🥑', '🍎']
# len(s) 👈 length of s
print(len(squares))
# min(s) 👈 smallest item of s
print(min(squares))
# max(s) 👈 largest item of s
print(max(squares))
# s.index(x[, i[, j]]) 👈 index of the first occurrence of x in s (at or after index i and before index j)
print(fruits_copy.index('🥭', 2, 4))
# s.count(x) 👈 total number of occurrences of x in s
print(fruits_copy.count('🥭'))
# s.append(x) 👈 appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
fruits_copy.append("🍊")
print(fruits_copy) # ['🍒', '🍌', '🍎', '🍒', '🍌', '🍎', '🥑', '🍊']
# s.clear() 👈 removes all items from s (same as del s[:])
fruits_copy.clear()
print(fruits_copy) # []
# s.extend(t) or s += t 👈 extends s with the contents of t (for the most part the same as s[len(s):len(s)] = t)
fruits_copy.extend(fruits)
print(fruits_copy) # ['🍎', '🍌', '🍒', '🥭']
# s *= n 👈 updates s with its contents repeated n times
fruits_copy *= 2
print(fruits_copy) # ['🍎', '🍌', '🍒', '🥭', '🍎', '🍌', '🍒', '🥭']
# s.insert(i, x) 👈 inserts x into s at the index given by i (same as s[i:i] = [x])
fruits_copy.insert(1, "🥑")
print(fruits_copy) # ['🍎', '🥑', '🍌', '🍒', '🥭', '🍎', '🍌', '🍒', '🥭']
# s.pop() or s.pop(i) 👈 retrieves the item at i and also removes it from s
print(fruits_copy.pop()) # 🥭
# s.remove(x) 👈 remove the first item from s where s[i] is equal to x
fruits_copy.remove("🥭")
print(fruits_copy) # ['🍎', '🥑', '🍌', '🍒', '🍎', '🍌', '🍒']
# s.reverse() 👈 reverses the items of s in place
fruits_copy.reverse()
print(fruits_copy) # ['🍒', '🍌', '🍎', '🍒', '🍌', '🥑', '🍎']
In [ ]:
Copied!
# sorting
from random import randint
random_numbers = [randint(0, 100) for _ in range(10)]
print(random_numbers)
random_numbers.sort()
print(random_numbers)
random_numbers.sort(reverse=True)
print(random_numbers)
random_numbers.sort(key=lambda x: x > 50, reverse=False)
print(random_numbers)
# sorting
from random import randint
random_numbers = [randint(0, 100) for _ in range(10)]
print(random_numbers)
random_numbers.sort()
print(random_numbers)
random_numbers.sort(reverse=True)
print(random_numbers)
random_numbers.sort(key=lambda x: x > 50, reverse=False)
print(random_numbers)