Learn R Programming  /  Data Structures  /  List

List

A list is R's flexible, all-purpose container. Unlike a vector, a single list can hold numbers, text, vectors, data frames, and even other lists at the same time.

Creating a List

Use list() to build a list. Each element can be a different type or structure.

R Code
student <- list(
  name    = "Meera",
  age     = 23,
  passed  = TRUE,
  scores  = c(88, 92, 79)
)

student
Output
$name
[1] "Meera"

$age
[1] 23

$passed
[1] TRUE

$scores
[1] 88 92 79

Accessing List Elements: [ ] vs [[ ]]

This trips up almost every beginner, so read carefully:

  • [ ] single brackets return a smaller list containing that element
  • [[ ]] double brackets return the actual value inside, unwrapped
  • $name is a shortcut for [["name"]] when the element is named
R Code
student[1]      # returns a list containing "name"
class(student[1])

student[[1]]    # returns the actual character value
class(student[[1]])

student$name  # same result as [[1]], using the name
Output
$name
[1] "Meera"

[1] "list"
[1] "Meera"
[1] "character"
[1] "Meera"
💡 Tip
Think of a list as a row of labelled boxes. [ ] hands you the box (still wrapped); [[ ]] opens the box and hands you what is inside.

Modifying Lists

Add, change, or remove elements using the same $ or [[ ]] syntax used for reading.

R Code
student$grade <- "A"          # add a new element
student$age   <- 24            # update an existing element
student$passed <- NULL          # remove an element (set to NULL)

names(student)
Output
[1] "name"   "age"    "scores" "grade" 

Nested Lists

Lists can contain other lists, which is how R represents deeply structured data (for example, a JSON response from an API).

R Code
company <- list(
  name = "DataCorp",
  ceo  = list(name = "Zayn", age = 41),
  employees = 120
)

company$ceo$name        # chain $ to reach nested values
company[["ceo"]][["age"]]
Output
[1] "Zayn"
[1] 41

Looping Over a List

R Code
scores <- list(Math = 90, Physics = 85, Biology = 78)

for (subject in names(scores)) {
  cat(subject, ":", scores[[subject]], "\n")
}
Output
Math : 90 
Physics : 85 
Biology : 78

Advanced: Converting a List of Records to a Data Frame

🚀 Advanced Example
A very common real-world pattern: you receive data as a list of similarly-shaped records (e.g. from an API) and need it as a tidy data frame.
R Code
records <- list(
  list(name = "Rafi",  score = 88),
  list(name = "Meera", score = 92),
  list(name = "Zayn",  score = 76)
)

df <- do.call(rbind.data.frame, records)
df
Output
   name score
1  Rafi    88
2 Meera    92
3  Zayn    76

Key Points

  • A list can mix any types and structures, unlike a vector.
  • Single brackets [ ] keep the list wrapper; double brackets [[ ]] unwrap the value.
  • $name is shorthand for [[\"name\"]] on named lists.
  • Setting an element to NULL removes it from the list.