0% found this document useful (0 votes)
8 views2 pages

Python Cheat Sheet: Data Structures

This document is a Python cheat sheet that provides a concise overview of essential methods and functions for strings, lists, tuples, and dictionaries. Each section includes examples and outputs for various operations, such as string manipulation, list methods, tuple operations, and dictionary functions. It serves as a quick reference guide for Python programming.

Uploaded by

kanishkpanwar999
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

Python Cheat Sheet: Data Structures

This document is a Python cheat sheet that provides a concise overview of essential methods and functions for strings, lists, tuples, and dictionaries. Each section includes examples and outputs for various operations, such as string manipulation, list methods, tuple operations, and dictionary functions. It serves as a quick reference guide for Python programming.

Uploaded by

kanishkpanwar999
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Cheat Sheet – Strings, Lists, Tuples,

Dictionaries

1. Strings (str)
Function / Method Example Output
len(s) len("hello") 5
[Link]() "HELLO".lower() "hello"
[Link]() "hello".upper() "HELLO"
[Link]() "hello world".title() "Hello World"
[Link]() "hello".capitalize() "Hello"
[Link]() " hi ".strip() "hi"
[Link](sep) "a,b,c".split(",") ['a','b','c']
[Link](list) ",".join(['a','b','c']) "a,b,c"
[Link](old,new) "hello".replace("h","j") "jello"
[Link](sub) "hello".find("l") 2
[Link](sub) "hello".count("l") 2
[Link](sub) "hello".startswith("he") True
[Link](sub) "hello".endswith("lo") True
[Link]() "hello".isalpha() True
[Link]() "123".isdigit() True
f"{var}" name="A"; f"Hi {name}" "Hi A"

2. Lists (list)
Method Example Output
len(lst) len([1,2,3]) 3
[Link](x) [1,2].append(3) [1,2,3]
[Link](i,x) [1,3].insert(1,2) [1,2,3]
[Link](list2) [1,2].extend([3,4]) [1,2,3,4]
[Link](x) [1,2,3].remove(2) [1,3]
[Link](i=-1) [1,2,3].pop() 3
[Link](x) [1,2,3].index(2) 1
[Link](x) [1,2,2].count(2) 2
[Link]() [3,1,2].sort() [1,2,3]
[Link]() [1,2,3].reverse() [3,2,1]
[Link]() [1,2,3].copy() [1,2,3]
[Link]() [1,2,3].clear() []
3. Tuples (tuple)
Method / Operation Example Output
len(t) len((1,2,3)) 3
[Link](x) (1,2,2).count(2) 2
[Link](x) (1,2,3).index(2) 1
t1 + t2 (1,2) + (3,4) (1,2,3,4)
t * n (1,2)*2 (1,2,1,2)
x in t 2 in (1,2,3) True

Tuples are immutable, no append/remove.

4. Dictionaries (dict)
Method Example Output
len(d) len({'a':1}) 1
d[key] {'a':1}['a'] 1
[Link](key,default) {'a':1}.get('b',0) 0
[Link]() {'a':1,'b':2}.keys() dict_keys(['a','b'])
[Link]() {'a':1,'b':2}.values() dict_values([1,2])
dict_items([('a',1),('b',2)
[Link]() {'a':1,'b':2}.items()
])
[Link](d2) {'a':1}.update({'b':2}) {'a':1,'b':2}
[Link](key) {'a':1}.pop('a') 1
[Link]() {'a':1,'b':2}.popitem() ('b',2)
[Link]() {'a':1}.clear() {}
key in d 'a' in {'a':1} True
[Link]() {'a':1}.copy() {'a':1}
[Link](seq,value [Link](['a','b'],0
{'a':0,'b':0}
) )

Common questions

Powered by AI

The 'lst.sort()' method sorts a list in place, modifying the original list and not returning a new one. This approach conserves memory resources because no additional space is required for sorting, important in systems with limited memory when handling large lists . However, this method's in-place nature requires careful design consideration in algorithmic contexts where the preservation of the original list data is necessary, as it is altered permanently. The decision to use in-place sorting should factor in whether post-sort access to the original unsorted data is needed, in which case 'sorted()' might be the preferable choice since it returns a new sorted list while leaving the original list intact . Thus, 'lst.sort()' should be employed in scenarios where memory efficiency is prioritized over data retention.

Tuples in Python are immutable, meaning once they are created, their elements cannot be changed. This makes tuples more memory efficient and potentially faster when performing operations on them compared to lists because the memory layout is fixed . Lists, however, are mutable, allowing for dynamic modifications such as appending, removing, or changing elements, which makes them more flexible but can incur additional overhead due to the need for dynamic memory allocation. Thus, tuples are typically used for fixed collections of items, such as returning multiple values from a function, where the included data is not meant to change .

Using 'dict.fromkeys(seq, value)' allows the creation of a dictionary with keys from 'seq', all initialized to the same 'value'. This method provides a quick and concise approach to generating a dictionary where all keys need to have an identical initial value, which can simplify initial setup for data structures where uniform initialization is needed . However, a potential drawback is when 'value' is a mutable object, changes to the object via any dictionary key will affect all keys, which may not be the desired behavior if independent values are needed for each key . Thus, it is best used with immutable values or when uniformity is desired across all keys.

The method 'sep.join(list)' combines elements of a list into a single string with each element separated by the 'sep' string. For example, using ','.join(['a','b','c']) results in the string 'a,b,c' . Conversely, 's.split(sep)' takes a string and splits it into a list using the specified separator 'sep', such as splitting 'a,b,c' with ',' producing the list ['a', 'b', 'c']. Together, these operations provide a reversible way to convert between strings and lists, useful for tasks like data serialization or formatting, where data consistently needs to change form between a stored format and a usable list of elements .

The operation 't1 + t2' concatenates two tuples, allowing the combination of disparate data sources into a single tuple, which can be particularly useful for aggregating results or forming complex data structures from simpler elements without altering the original tuples since they are immutable . The operation 't * n' creates a new tuple by repeating the existing tuple 't', 'n' times. This can be used to efficiently initialize a data structure with a predetermined pattern or sequence without manually entering repeated data . These operations are computationally efficient due to the fixed size and immutability of tuples, making them suitable for performance-critical applications where data duplications and extensions are required.

The 's.isalpha()' and 's.isdigit()' methods are useful for data validation as they allow straightforward checks to ensure string content adheres to expected character types, which is a common requirement in data validation processes. 's.isalpha()' can confirm that a string only contains alphabetic characters, useful for validating user inputs such as names where numerical or special characters are disallowed . Similarly, 's.isdigit()' verifies that a string consists solely of digit characters, aiding in checks for numeric inputs where letters or special characters would be erroneous, such as validating age or phone numbers . These methods help maintain data integrity by quickly identifying format violations.

The method 'd.pop(key)' removes and returns the value for the specified key, allowing for the removal of a specific item from the dictionary by key. This is best used when you know the exact key of the item you want to remove . On the other hand, 'd.popitem()' removes and returns an arbitrary (key, value) pair from the dictionary, typically the last inserted item in Python 3.7 and later, as dictionaries maintain insertion order. 'd.popitem()' is suitable for algorithms or processes where items are processed in a last-in, first-out order or when you want to iterate through and empty a dictionary until only required elements remain .

The 'list.sort()' method modifies the list in place and does not return a new list, which is memory efficient because it doesn't require additional space for a new list, helping in memory management when dealing with large datasets. In contrast, the 'sorted()' function creates a new list and thus, uses more memory due to the additional space needed to store the sorted list . Both use Timsort with a worst-case time complexity of O(n log n). The choice between them depends on the requirement: in-place sorting with 'list.sort()' is efficient if the original list can be discarded or doesn't need to be retained in its original form, whereas 'sorted()' is useful when the original list needs to be preserved .

The 'lst.copy()' method creates a shallow copy of the list, meaning it copies only the outer structure of the list, but not the elements themselves if they are also mutable objects like lists, dictionaries, or custom objects . This has implications for nested data structures; changes made to mutable elements in the copied list will reflect in the original list and vice versa. When dealing with complex data structures where independence from the original is required, a deep copy approach using the 'copy.deepcopy()' function is necessary to duplicate both the outer structure and the content fully . Inadequate attention to this can lead to unexpected behavior and bugs in programs handling nested collections.

The 'f"{var}"' syntax, known as f-strings, offers clear and concise syntax for embedding expressions inside string literals, enhancing readability by showing expressions directly inside the string . Compared to 's.format()', which is more verbose and slightly slower due to requiring a function call and indexing, f-strings provide better performance and are favored for simpler expressions . The older '%' formatting is less readable due to its special characters and lack of typing flexibility, and has generally been superseded by 'format()' and f-strings. F-strings also perform better because they use the same mechanism as literal string concatenation, making them more efficient in scenarios where performance is crucial .

You might also like