v9.1.1
Menu

Create Tensor from List

easyFREEBasic OpsPyTorch BasicsPytorch

Problem Statement

Create a PyTorch tensor from a nested Python list.

Background

Tensors are the fundamental data structure in PyTorch. They are similar to NumPy arrays but can run on GPUs. Creating tensors from Python lists is the most basic operation.

Your Task

Write a function create_tensor_from_list(data) that takes a nested Python list and returns a PyTorch tensor.

Output Format

Your function must return a PyTorch tensor with the same shape and the same values as the input. The test prints the returned tensor directly, so integer inputs must stay integers (printed as 1, not 1.).

Example

Input
[[1, 2], [3, 4]]
Output
tensor([[1, 2],
        [3, 4]])
Reasoning
  • Input: data is [[1, 2], [3, 4]], a list of 2 rows, each a list of 2 integers. Read it as a 2×22 \times 2 matrix with entries a11=1a_{11}=1, a12=2a_{12}=2, a21=3a_{21}=3, a22=4a_{22}=4.
  • Shape: the nesting depth gives the number of dimensions (2), and the lengths at each level give the sizes: 2 rows by 2 columns. Equal-length rows make it a rectangular grid.
  • Values: nothing is computed. Row ii, column jj of the tensor holds exactly aija_{ij}, so the first row is (1,2)(1, 2) and the second is (3,4)(3, 4).
  • Number type: every entry is a whole number, so the tensor stores 64-bit integers. That is why the output shows plain whole numbers; a floating-point tensor would print a trailing decimal point after every value (1. instead of 1).
  • Output: a 2×22 \times 2 integer tensor whose rows print as [[1, 2], [3, 4]], matching the input exactly. Notice that a single value like [[5]] still keeps both levels of nesting and becomes a 1×11 \times 1 tensor, not a plain number.

Constraints

  • Input will always be a valid nested list of numbers
  • The inner lists will all have the same length
  • Values will be integers between -1000 and 1000

Learn this in

More from Pytorch

solution.py

Test results

Sign in to run your code against the test cases.