Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Python lists, sets, and tuples

This cheat sheet provides a comprehensive overview of Python lists, sets, and tuples, including their creation, initialization, and various operations such as adding, removing, accessing, and manipulating elements. It also covers advanced operations like comprehensions, conversions between types, and iterating techniques. The document serves as a quick reference for common tasks and functions associated with these data structures.

Uploaded by

vamsitarak55
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Python lists, sets, and tuples

This cheat sheet provides a comprehensive overview of Python lists, sets, and tuples, including their creation, initialization, and various operations such as adding, removing, accessing, and manipulating elements. It also covers advanced operations like comprehensions, conversions between types, and iterating techniques. The document serves as a quick reference for common tasks and functions associated with these data structures.

Uploaded by

vamsitarak55
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

# [ Python lists, sets, and tuples ] ( CheatSheet )

#_ [ Lists ]

Creating and Initializing

● Create an empty list: my_list = []


● Create a list with elements: my_list = [1, 2, 3]
● List comprehension: squares = [x**2 for x in range(10)]
● Nested list comprehension: matrix = [[i+j for j in range(3)] for i in
range(4)]

Adding Elements

● Append an element: my_list.append(4)


● Extend with another list: my_list.extend([5, 6, 7])
● Insert an element at a specific position: my_list.insert(0, 'start')

Accessing Elements

● Access by index: element = my_list[0]


● Access last element: last_element = my_list[-1]
● Slicing: sub_list = my_list[1:3]

Removing Elements

● Remove an element by value: my_list.remove('start')


● Remove an element by index and get its value: element = my_list.pop(1)
● Clear all elements: my_list.clear()

Searching and Sorting

● Find index of an element: index = my_list.index(4)


● Count occurrences: count = my_list.count(4)
● Sort the list: my_list.sort()
● Sort in descending order: my_list.sort(reverse=True)

Reversing

● Reverse the list: my_list.reverse()

By: Waleed Mousa


● Reversed copy: reversed_list = my_list[::-1]

Miscellaneous

● Length of list: length = len(my_list)


● Sum of elements: total = sum(my_list)
● List membership test: exists = 4 in my_list
● Concatenate lists: concatenated = my_list + another_list
● Multiply list (repeating): repeated = my_list * 2
● Convert tuple to list: my_list = list(my_tuple)
● Filter list: filtered = list(filter(lambda x: x%2 == 0, my_list))
● Map function over list: squared = list(map(lambda x: x**2, my_list))

List to String and Vice Versa

● Join list into string: str_list = ' '.join(['Hello', 'World'])


● Split string into list: list_str = 'Hello World'.split(' ')

Copying

● Shallow copy of a list: list_copy = my_list.copy()


● Deep copy of a list (for lists of lists): import copy; list_deep_copy =
copy.deepcopy(my_list)

Nested Lists

● Flatten a nested list: flattened = [item for sublist in nested_list for


item in sublist]
● Matrix transposition: transposed = list(zip(*matrix))

Iterating

● Enumerate (with index and value): for index, value in enumerate(my_list):


print(index, value)
● List with index-value pairs: indexed_list = list(enumerate(my_list))

Advanced List Operations

● Circular list access (using modulo): item = my_list[i % len(my_list)]


● Find multiple items: found_items = [x for x in my_list if x in
set_of_interest]

By: Waleed Mousa


● Remove duplicates: no_duplicates = list(dict.fromkeys(my_list))
● Interleave two lists: interleaved = [val for pair in zip(list1, list2)
for val in pair]

#_ [ Sets ]

Creating and Initializing

● Create an empty set: my_set = set()


● Create a set with elements: my_set = {1, 2, 3}

Adding and Removing Elements

● Add an element: my_set.add(4)


● Remove an element safely: my_set.discard(4)
● Remove an element and raise KeyError if not found: my_set.remove(3)

Set Operations

● Union of two sets: union_set = my_set | another_set


● Intersection of two sets: intersection_set = my_set & another_set
● Difference of two sets: difference_set = my_set - another_set
● Symmetric difference (elements in either set, but not both):
symmetric_difference = my_set ^ another_set

Set Comprehensions

● Set comprehension: squared_set = {x**2 for x in range(10)}

Advanced Set Operations

● Immutable set (frozenset): immutable_set = frozenset([1, 2, 3])


● Set difference (alternative): difference_set =
my_set.difference(another_set)
● Symmetric difference update: my_set ^= another_set
● Convert set to list: my_list = list(my_set)

Miscellaneous

● Set membership test: exists = 4 in my_set


● Length of set: length = len(my_set)

By: Waleed Mousa


● Convert list to set (for removing duplicates): my_set = set(my_list)
● Subset check: is_subset = {1, 2}.issubset(my_set)
● Superset check: is_superset = my_set.issuperset({1, 2})
● Intersection update: my_set &= another_set
● Difference update: my_set -= another_set

#_ [ Tuples ]

Creating and Initializing

● Create an empty tuple: my_tuple = ()


● Single element tuple (note the comma): single = (1,)
● Create a tuple: my_tuple = (1, 2, 3)

Accessing Elements

● Access by index: element = my_tuple[0]


● Negative indexing: last_element = my_tuple[-1]
● Slicing: sub_tuple = my_tuple[1:3]

Tuple Operations

● Tuple with mixed types: mixed_tuple = (1, 'a', [2, 'b'])


● Tuple repetition: repeated_tuple = my_tuple * 2
● Concatenate tuples: concatenated_tuple = my_tuple + another_tuple

Advanced Tuple Usage

● Named tuples (for readable, self-documenting code):

from collections import namedtuple

Person = namedtuple('Person', 'name age')

person = Person(name='John', age=30)

● Tuple as dictionary key: dict_with_tuple_keys = {(1, 2): 'tuple_as_key'}

Iterating Over Tuples

● Iterate over tuple: for item in my_tuple: print(item)

By: Waleed Mousa


● Enumerate over tuple: for index, value in enumerate(my_tuple):
print(index, value)

Miscellaneous

● Tuple membership test: exists = 1 in my_tuple


● Length of tuple: length = len(my_tuple)
● Count occurrences of an element: count = my_tuple.count(1)
● Find index of an element: index = my_tuple.index(2)
● Convert list to tuple: my_tuple = tuple(my_list)
● Unpack tuple: a, b, c = my_tuple
● Nested tuple unpacking: ((a, b), c) = ((1, 2), 3)
● Concatenate tuples: concatenated = my_tuple + another_tuple
● Multiply tuple (repeating): repeated = my_tuple * 2
● Min and max of tuple: min_val, max_val = min(my_tuple), max(my_tuple)
● Max and min values in a tuple: max_val, min_val = max(my_tuple),
min(my_tuple)
● Sum of elements in a tuple (if numbers): total = sum(my_tuple)
● Count occurrences of an element in a tuple: count = my_tuple.count(1)
● Index of an element in a tuple: index = my_tuple.index(1)

Conversions Between Types

● List to set (to remove duplicates): unique_items = set(my_list)


● Set to list (for indexing): list_from_set = list(my_set)
● List to tuple (for immutability): tuple_from_list = tuple(my_list)
● Tuple to list (for mutability): list_from_tuple = list(my_tuple)

Advanced Data Structure Manipulations

● Zip lists into list of tuples: zipped_list = list(zip(list1, list2))


● Unzip list of tuples into separate lists: list1, list2 =
zip(*zipped_list)
● Sort a list of tuples by the second item: sorted_by_second =
sorted(list_of_tuples, key=lambda x: x[1])
● Sort a list of dictionaries by a specific key: sorted_dicts =
sorted(list_of_dicts, key=lambda x: x['key'])

By: Waleed Mousa

You might also like