Bird
Raised Fist0
NumPydata~10 mins

String type in NumPy - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - String type in NumPy
Create NumPy array with strings
↓
Array stores fixed-length strings
↓
Access or modify elements
↓
Observe dtype and behavior
We create a NumPy array of strings, which stores fixed-length strings internally. We can access or change elements and observe how NumPy handles string data.
Execution Sample
NumPy
import numpy as np
arr = np.array(['cat', 'dog', 'bird'])
print(arr)
print(arr.dtype)
arr[1] = 'fish'
print(arr)
Create a NumPy array of strings, print it and its type, change one element, then print the array again.
Execution Table
StepActionArray ContentdtypeNotes
1Create array with ['cat', 'dog', 'bird']['cat' 'dog' 'bird']dtype('<U4')Strings stored as fixed-length Unicode of length 4
2Print array['cat' 'dog' 'bird']dtype('<U4')Output shows all strings
3Print dtypeN/Adtype('<U4')dtype shows Unicode strings of max length 4
4Assign 'fish' to arr[1]['cat' 'fish' 'bird']dtype('<U4')'fish' fits max length 4, replaces 'dog'
5Print array after change['cat' 'fish' 'bird']dtype('<U4')Array updated with new string
6Assign 'elephant' to arr[0]['elep' 'fish' 'bird']dtype('<U4')String truncated to 4 chars due to fixed length
7Print array after truncation['elep' 'fish' 'bird']dtype('<U4')Long string cut to fit dtype length
💡 Array stores fixed-length Unicode strings; longer strings get truncated to dtype max length.
Variable Tracker
VariableStartAfter Step 1After Step 4After Step 6Final
arrundefined['cat' 'dog' 'bird']['cat' 'fish' 'bird']['elep' 'fish' 'bird']['elep' 'fish' 'bird']
Key Moments - 2 Insights
Why does assigning 'elephant' to arr[0] result in 'elep' instead of the full word?
NumPy arrays with string dtype store fixed-length strings. The dtype '<U4' means max 4 characters. Longer strings get cut off to fit, as shown in execution_table step 6.
What does dtype '<U4' mean in the context of the string array?
It means Unicode strings with a fixed max length of 4 characters. This is why all strings in the array have length up to 4, as seen in step 1 and 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 4. What is the content of the array after assigning 'fish' to arr[1]?
A['cat' 'dog' 'bird']
B['cat' 'fish' 'bird']
C['cat' 'fish' 'fish']
D['cat' 'dog' 'fish']
💡 Hint
Check the 'Array Content' column at step 4 in the execution_table.
At which step does the array first show truncated string values?
AStep 4
BStep 2
CStep 6
DStep 1
💡 Hint
Look for when 'elephant' is assigned and truncated in the execution_table.
If the dtype was '<U10' instead of '<U4', what would happen when assigning 'elephant' to arr[0]?
AIt would store the full 'elephant' string
BIt would be truncated to 4 characters
CIt would cause an error
DIt would store only the first character
💡 Hint
Consider dtype max length and how it affects string storage shown in variable_tracker.
Concept Snapshot
NumPy string arrays store fixed-length Unicode strings.
The dtype '<U4' means max 4 characters per string.
Assigning longer strings truncates them to dtype length.
Access and modify elements like normal arrays.
Useful for consistent string length storage in arrays.
Full Transcript
This visual execution shows how NumPy handles string arrays. We start by creating an array of strings ['cat', 'dog', 'bird']. NumPy stores these as fixed-length Unicode strings with dtype '<U4', meaning max 4 characters. When we print the array and its dtype, we see the strings and the type. Changing an element to 'fish' works fine because 'fish' fits in 4 characters. But assigning 'elephant' to an element truncates it to 'elep' because of the fixed length. This behavior is important to understand when working with string data in NumPy arrays.

Practice

(1/5)
1. Which NumPy string type should you use to store Unicode text like emojis or accented characters?
easy
A. Use 'U' type for Unicode strings.
B. Use 'S' type for Unicode strings.
C. Use 'i' type for Unicode strings.
D. Use 'f' type for Unicode strings.

Solution

  1. Step 1: Understand NumPy string types

    NumPy has two main string types: 'S' for byte strings (ASCII) and 'U' for Unicode strings.
  2. Step 2: Identify correct type for Unicode

    Unicode strings require 'U' type to support characters beyond ASCII, like emojis or accented letters.
  3. Final Answer:

    Use 'U' type for Unicode strings. -> Option A
  4. Quick Check:

    Unicode text = 'U' type [OK]
Hint: Unicode needs 'U', ASCII uses 'S' type [OK]
Common Mistakes:
  • Using 'S' type for Unicode causes data loss
  • Confusing numeric types with string types
  • Assuming 'U' is for byte strings
2. Which of the following is the correct way to create a NumPy array of byte strings with length 5?
easy
A. np.array(['hello', 'world'], dtype='int5')
B. np.array(['hello', 'world'], dtype='U5')
C. np.array(['hello', 'world'], dtype='S5')
D. np.array(['hello', 'world'], dtype='float5')

Solution

  1. Step 1: Identify byte string dtype syntax

    Byte strings use dtype='S' followed by the fixed length, e.g., 'S5' for length 5.
  2. Step 2: Check options for correct dtype

    np.array(['hello', 'world'], dtype='S5') uses 'S5', which is correct for byte strings of length 5.
  3. Final Answer:

    np.array(['hello', 'world'], dtype='S5') -> Option C
  4. Quick Check:

    Byte strings = 'S' + length [OK]
Hint: Byte strings use dtype='S' plus length number [OK]
Common Mistakes:
  • Using 'U' instead of 'S' for byte strings
  • Using invalid dtypes like 'int5' or 'float5'
  • Omitting the length number after 'S'
3. What will be the output of this code?
import numpy as np
arr = np.array(['cat', 'dog', 'elephant'], dtype='S5')
print(arr)
medium
A. ['cat' 'dog' 'eleph']
B. [b'cat' b'dog' b'eleph']
C. [b'cat' b'dog' b'elephant']
D. ['cat' 'dog' 'elephant']

Solution

  1. Step 1: Understand dtype='S5' effect

    Using dtype='S5' means fixed-length byte strings of length 5, so strings longer than 5 characters get truncated.
  2. Step 2: Check each string length and truncation

    'cat' and 'dog' fit within 5 bytes, but 'elephant' is longer and gets truncated to 'eleph'.
  3. Final Answer:

    [b'cat' b'dog' b'eleph'] -> Option B
  4. Quick Check:

    Fixed length 5 truncates 'elephant' to 'eleph' [OK]
Hint: Fixed-length strings truncate longer text [OK]
Common Mistakes:
  • Expecting full 'elephant' without truncation
  • Confusing byte strings with Unicode strings
  • Ignoring the 'b' prefix for byte strings
4. The following code throws an error. What is the main issue?
import numpy as np
arr = np.array(['a', 'b', 'c'], dtype='U2')
arr[0] = 'abc'
medium
A. The array must be created with dtype='S3' to assign 'abc'.
B. You cannot assign strings to NumPy arrays.
C. dtype='U2' only supports byte strings, not Unicode.
D. The string 'abc' is longer than dtype='U2' allows.

Solution

  1. Step 1: Understand dtype='U2' limitation

    dtype='U2' means Unicode strings of fixed length 2 characters only.
  2. Step 2: Check assigned string length

    Trying to assign 'abc' (3 characters) to an element that only allows 2 characters causes truncation or error.
  3. Final Answer:

    The string 'abc' is longer than dtype='U2' allows. -> Option D
  4. Quick Check:

    Fixed-length Unicode strings truncate or error on longer input [OK]
Hint: Check string length vs dtype length before assignment [OK]
Common Mistakes:
  • Thinking dtype='U2' supports any length string
  • Believing NumPy arrays can't hold strings
  • Confusing byte strings ('S') with Unicode ('U')
5. You have a list of mixed-length Unicode strings: ['hi', 'hello', 'hey', 'hola']. You want to create a NumPy array that stores all strings without truncation. Which dtype should you choose?
hard
A. dtype='U5' because the longest string has 5 characters.
B. dtype='S5' because it supports Unicode strings up to length 5.
C. dtype='U4' because it is the default for Unicode strings.
D. dtype='S10' to allow extra space for all strings.

Solution

  1. Step 1: Find the longest string length

    The longest string is 'hello' with 5 characters.
  2. Step 2: Choose dtype to fit longest string

    Use dtype='U5' to store Unicode strings up to length 5 without truncation.
  3. Step 3: Avoid byte string dtype for Unicode

    Using 'S' type stores byte strings, not Unicode, so it may cause data loss.
  4. Final Answer:

    dtype='U5' because the longest string has 5 characters. -> Option A
  5. Quick Check:

    Unicode max length = dtype='U' + max length [OK]
Hint: Match dtype length to longest Unicode string [OK]
Common Mistakes:
  • Using 'S' dtype for Unicode strings
  • Choosing dtype length smaller than longest string
  • Assuming default dtype fits all strings
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard